WanderingAIWaypoints.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3. public class WanderingAIWaypoints : MonoBehaviour
  4. {
  5. public Transform[] waypoints;
  6. public float wanderTimer;
  7. public float targetScattering = 5.0f; //Streuung
  8. private Animator anim;
  9. private NavMeshAgent agent;
  10. private float timer;
  11. private int prevWP = -1;
  12. private Vector3 target;
  13. // Use this for initialization
  14. void Start()
  15. {
  16. agent = this.GetComponent<NavMeshAgent>();
  17. anim = this.GetComponent<Animator>();
  18. anim.SetBool("isWalking", false);
  19. anim.SetBool("isIdle", true);
  20. timer = wanderTimer;
  21. }
  22. private void FixedUpdate()
  23. {
  24. timer += Time.deltaTime;
  25. if (timer >= wanderTimer)
  26. {
  27. if (waypoints.Length == 0) return;
  28. int currentWP = Random.Range(0, waypoints.Length);
  29. // Until previous and current WP are no longer the same, otherwise double waiting time for same WP
  30. while(prevWP == currentWP)
  31. currentWP = Random.Range(0, waypoints.Length);
  32. prevWP = currentWP;
  33. target = checkTarget(waypoints[currentWP].transform.position, targetScattering);
  34. if(target.x != float.PositiveInfinity)
  35. {
  36. if (agent.isActiveAndEnabled)
  37. agent.SetDestination(target);
  38. anim.SetBool("isWalking", true);
  39. anim.SetBool("isIdle", false);
  40. timer = 0;
  41. }
  42. else
  43. {
  44. timer = wanderTimer;
  45. }
  46. }
  47. else
  48. {
  49. // if x and z coordinates of newPos are the same as the position, humans reached destination and idle animation can start
  50. if (target.x == transform.position.x && target.z == transform.position.z)
  51. {
  52. anim.SetBool("isWalking", false);
  53. anim.SetBool("isIdle", true);
  54. }
  55. }
  56. }
  57. public static Vector3 checkTarget(Vector3 target, float dist)
  58. {
  59. Vector3 modifiedTarget = Random.insideUnitSphere * dist + target;
  60. // SamplePosition also checks the y axis. However, this is not relevant for me, so valid positions (x & z) are also discarded.
  61. // -3.6f is the only valid entry for y
  62. modifiedTarget = new Vector3(modifiedTarget.x, -3.6f, modifiedTarget.z);
  63. NavMeshHit navHit;
  64. NavMesh.SamplePosition(modifiedTarget, out navHit, 1.0f, -1);
  65. return navHit.position;
  66. }
  67. }