RandomWalk.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //======= Copyright (c) Stereolabs Corporation, All rights reserved. ===============
  2. using UnityEngine;
  3. using UnityEngine.AI;
  4. /// <summary>
  5. /// Tells the attached NavMeshAgent component to walk to a random location, and finds a new location
  6. /// each time it arrives.
  7. /// Used in the ZED spatial mapping sample to make the bunny character walk around once you've finished
  8. /// scanning your environment.
  9. /// </summary>
  10. [RequireComponent(typeof(NavMeshAgent))]
  11. public class RandomWalk : MonoBehaviour
  12. {
  13. /// <summary>
  14. /// Maximum distance of the next random point to walk to.
  15. /// </summary>
  16. [Tooltip("Maximum distance of the next random point to walk to.")]
  17. public float maxRange = 25.0f;
  18. /// <summary>
  19. /// The NavMeshAgent component attached to this GameObject.
  20. /// </summary>
  21. private NavMeshAgent m_agent;
  22. /// <summary>
  23. /// Whether the agent should be walking.
  24. /// </summary>
  25. private bool startWalking = false;
  26. /// <summary>
  27. /// Current random destination the agent is walking toward.
  28. /// </summary>
  29. private Vector3 destination;
  30. /// <summary>
  31. /// Factor used to narrow the range of possible random destinations if positions at the range are difficult to find.
  32. /// </summary>
  33. private uint reduceFactor = 0;
  34. /// <summary>
  35. /// Enables the agent component and begins walking.
  36. /// Called by EnemyManager once the agent is successfully placed.
  37. /// </summary>
  38. public void Activate()
  39. {
  40. m_agent = GetComponent<NavMeshAgent>();
  41. m_agent.enabled = true;
  42. startWalking = true;
  43. }
  44. void Update()
  45. {
  46. if (startWalking)
  47. {
  48. if (m_agent.enabled)
  49. {
  50. if (m_agent.pathPending || m_agent.remainingDistance > 0.1f)
  51. {
  52. reduceFactor = 0;
  53. return;
  54. }
  55. destination = (Mathf.Abs(maxRange) - reduceFactor) * Random.insideUnitSphere;
  56. m_agent.destination = destination;
  57. if(reduceFactor < Mathf.Abs(maxRange)/2) reduceFactor++;
  58. }
  59. }
  60. }
  61. }