WanderingAI.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. private Transform target;
  9. private UnityEngine.AI.NavMeshAgent agent;
  10. private float timer;
  11. // Use this for initialization
  12. void Start()
  13. {
  14. agent = this.GetComponent<UnityEngine.AI.NavMeshAgent>();
  15. timer = wanderTimer;
  16. }
  17. // Update is called once per frame
  18. void Update()
  19. {
  20. timer += Time.deltaTime;
  21. if (timer >= wanderTimer)
  22. {
  23. Vector3 newPos = RandomNavSphere(transform.position, wanderRadius, -1);
  24. Debug.Log("New Pos: " + newPos.ToString());
  25. agent.SetDestination(newPos);
  26. timer = 0;
  27. }
  28. }
  29. public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask)
  30. {
  31. Vector3 randDirection = Random.insideUnitSphere * dist;
  32. randDirection += origin;
  33. UnityEngine.AI.NavMeshHit navHit;
  34. UnityEngine.AI.NavMesh.SamplePosition(randDirection, out navHit, dist, layermask);
  35. return navHit.position;
  36. }
  37. }