WanderingAIOld.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3. public class WanderingAIOld : MonoBehaviour
  4. {
  5. public float wanderRadius;
  6. public float wanderTimer;
  7. private Animator anim;
  8. private NavMeshAgent agent;
  9. private float timer;
  10. private Vector3 newPos;
  11. // Use this for initialization
  12. void Start()
  13. {
  14. agent = this.GetComponent<NavMeshAgent>();
  15. anim = this.GetComponent<Animator>();
  16. anim.SetBool("isWalking", false);
  17. anim.SetBool("isIdle", true);
  18. newPos = RandomNavSphere(transform.position, wanderRadius, -1);
  19. timer = wanderTimer;
  20. }
  21. // Update is called once per frame
  22. void Update()
  23. {
  24. timer += Time.deltaTime;
  25. //Debug.Log("Pos: "+ transform.position);
  26. if (timer >= wanderTimer)
  27. {
  28. // generating random destination position
  29. newPos = RandomNavSphere(transform.position, wanderRadius, -1);
  30. if(agent.isActiveAndEnabled)
  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. NavMeshHit navHit;
  50. NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);
  51. return navHit.position;
  52. }
  53. }