NavMeshAgentController.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //======= Copyright (c) Stereolabs Corporation, All rights reserved. ===============
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.AI;
  5. /// <summary>
  6. /// Used in the ZED spatial mapping sample scene to position new nav mesh agents randomly onto a
  7. /// new NaVMesh when they're spawned.
  8. /// </summary>
  9. public class NavMeshAgentController : MonoBehaviour
  10. {
  11. /// <summary>
  12. /// Maximum distance between the starting position where the agent can be randomly placed.
  13. /// </summary>
  14. [Tooltip("Maximum distance between the starting position where the agent can be randomly placed.")]
  15. public float rangeAroundCurrentPosition = 5.0f;
  16. /// <summary>
  17. /// Finds a random position around a given point. The position will always be on the ground.
  18. /// </summary>
  19. /// <param name="center">The point around where the random position appears.</param>
  20. /// <param name="range">The maximum distance from the center that the random position can be.</param>
  21. /// <param name="result">The random position.</param>
  22. /// <returns>True if it found a valid location.</returns>
  23. bool RandomPoint(Vector3 center, float range, out Vector3 result)
  24. {
  25. //Try up to 30 times to find a valid point near center. Return true as soon as one is found.
  26. for (int i = 0; i < 30; i++)
  27. {
  28. Vector3 vector = Random.insideUnitSphere * range;
  29. if (Vector3.Dot(vector, -Vector3.up) < 0)
  30. {
  31. vector = -vector;
  32. }
  33. RaycastHit rayHit;
  34. if (!Physics.Raycast(center + transform.up, vector, out rayHit))
  35. {
  36. continue;
  37. }
  38. Vector3 randomPoint = rayHit.point;
  39. NavMeshHit hit;
  40. if (NavMesh.SamplePosition(randomPoint, out hit, 1.0f, NavMesh.AllAreas))
  41. {
  42. result = hit.position;
  43. return true;
  44. }
  45. }
  46. result = Vector3.zero;
  47. return false;
  48. }
  49. /// <summary>
  50. /// Sets the target position of the agent to a random point
  51. /// </summary>
  52. /// <returns>True if it successfully placed the agent. </returns>
  53. public bool Move()
  54. {
  55. Vector3 point;
  56. if (RandomPoint(transform.position, rangeAroundCurrentPosition, out point))
  57. {
  58. transform.position = point;
  59. return true;
  60. }
  61. return false;
  62. }
  63. }