Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. public class EnemyMovement: MonoBehaviour {
  4. // Fix a range how early u want your enemy detect the obstacle.
  5. private int range;
  6. private float speed;
  7. private bool isThereAnyThing = false;
  8. // Specify the target for the enemy.
  9. public GameObject target;
  10. private float rotationSpeed;
  11. private RaycastHit hit;
  12. // Use this for initialization
  13. void Start() {
  14. range = 80;
  15. speed = 10f;
  16. rotationSpeed = 15f;
  17. }
  18. // Update is called once per frame
  19. void Update() {
  20. //Look At Somthly Towards the Target if there is nothing in front.
  21. if (!isThereAnyThing) {
  22. Vector3 relativePos = target.transform.position - transform.position;
  23. Quaternion rotation = Quaternion.LookRotation(relativePos);
  24. transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime);
  25. }
  26. // Enemy translate in forward direction.
  27. transform.Translate(Vector3.forward * Time.deltaTime * speed);
  28. //Checking for any Obstacle in front.
  29. // Two rays left and right to the object to detect the obstacle.
  30. Transform leftRay = transform;
  31. Transform rightRay = transform;
  32. //Use Phyics.RayCast to detect the obstacle
  33. if (Physics.Raycast(leftRay.position + (transform.right * 7), transform.forward, out hit, range) || Physics.Raycast(rightRay.position - (transform.right * 7), transform.forward, out hit, range)) {
  34. if (hit.collider.gameObject.CompareTag("Obstacles")) {
  35. isThereAnyThing = true;
  36. transform.Rotate(Vector3.up * Time.deltaTime * rotationSpeed);
  37. }
  38. }
  39. // Now Two More RayCast At The End of Object to detect that object has already pass the obsatacle.
  40. // Just making this boolean variable false it means there is nothing in front of object.
  41. if (Physics.Raycast(transform.position - (transform.forward * 4), transform.right, out hit, 10) ||
  42. Physics.Raycast(transform.position - (transform.forward * 4), -transform.right, out hit, 10)) {
  43. if (hit.collider.gameObject.CompareTag("Obstacles")) {
  44. isThereAnyThing = false;
  45. }
  46. }
  47. // Use to debug the Physics.RayCast.
  48. Debug.DrawRay(transform.position + (transform.right * 7), transform.forward * 20, Color.red);
  49. Debug.DrawRay(transform.position - (transform.right * 7), transform.forward * 20, Color.red);
  50. Debug.DrawRay(transform.position - (transform.forward * 4), -transform.right * 20, Color.yellow);
  51. Debug.DrawRay(transform.position - (transform.forward * 4), transform.right * 20, Color.yellow);
  52. }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement