WanderingAI.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3. using System.Collections;
  4. public class WanderingAI : MonoBehaviour
  5. {
  6. public float wanderRadius;
  7. public float wanderTimer;
  8. Animator anim;
  9. private Transform target;
  10. private UnityEngine.AI.NavMeshAgent agent;
  11. private float timer;
  12. private Vector3 newPos;
  13. // Use this for initialization
  14. void Start()
  15. {
  16. agent = this.GetComponent<UnityEngine.AI.NavMeshAgent>();
  17. anim = this.GetComponent<Animator>();
  18. anim.SetBool("isWalking", true);
  19. anim.SetBool("isIdle", false);
  20. newPos = RandomNavSphere(transform.position, wanderRadius, -1);
  21. timer = wanderTimer;
  22. }
  23. // Update is called once per frame
  24. void Update()
  25. {
  26. timer += Time.deltaTime;
  27. if (timer >= wanderTimer)
  28. {
  29. // generating random destination position
  30. newPos = RandomNavSphere(transform.position, wanderRadius, -1);
  31. agent.SetDestination(newPos);
  32. anim.SetBool("isWalking", true);
  33. anim.SetBool("isIdle", false);
  34. timer = 0;
  35. } else
  36. {
  37. // if x and z coordinates of newPos are the same as the position, humans reached destination and idle animation can start
  38. if (newPos.x == transform.position.x && newPos.z == transform.position.z)
  39. {
  40. anim.SetBool("isWalking", false);
  41. anim.SetBool("isIdle", true);
  42. }
  43. }
  44. }
  45. public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask)
  46. {
  47. Vector3 randDirection = Random.insideUnitSphere * dist;
  48. randDirection += origin;
  49. UnityEngine.AI.NavMeshHit navHit;
  50. UnityEngine.AI.NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);
  51. return navHit.position;
  52. }
  53. }