Navigator.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace RootMotion.Demos
  5. {
  6. // Custom navigator for Unity Navigation.
  7. [System.Serializable]
  8. public class Navigator
  9. {
  10. public enum State
  11. {
  12. Idle,
  13. Seeking,
  14. OnPath,
  15. }
  16. [Tooltip("Should this Navigator be actively seeking a path.")]
  17. public bool activeTargetSeeking;
  18. [Tooltip("Increase this value if the character starts running in a circle, not able to reach the corner because of a too large turning radius.")]
  19. public float cornerRadius = 0.5f;
  20. [Tooltip("Recalculate path if target position has moved by this distance from the position it was at when the path was originally calculated")]
  21. public float recalculateOnPathDistance = 1f;
  22. //public float recalculateBadTargetDistance = 1f;
  23. [Tooltip("Sample within this distance from sourcePosition.")]
  24. public float maxSampleDistance = 5f;
  25. [Tooltip("Interval of updating the path")]
  26. public float nextPathInterval = 3f;
  27. /// <summary>
  28. /// Get the move direction vector (normalized). If nowhere to go or path finished, will return Vector3.zero.
  29. /// </summary>
  30. public Vector3 normalizedDeltaPosition { get; private set; }
  31. /// <summary>
  32. /// Get the current state of this Navigator (Idle, Seeking, OnPath).
  33. /// </summary>
  34. public State state { get; private set; }
  35. private Transform transform;
  36. private int cornerIndex;
  37. private Vector3[] corners = new Vector3[0];
  38. private UnityEngine.AI.NavMeshPath path;
  39. private Vector3 lastTargetPosition;
  40. private bool initiated;
  41. private float nextPathTime;
  42. public void Initiate(Transform transform)
  43. {
  44. this.transform = transform;
  45. path = new UnityEngine.AI.NavMeshPath();
  46. initiated = true;
  47. cornerIndex = 0;
  48. corners = new Vector3[0];
  49. state = State.Idle;
  50. lastTargetPosition = new Vector3(Mathf.Infinity, Mathf.Infinity, Mathf.Infinity);
  51. }
  52. public void Update(Vector3 targetPosition)
  53. {
  54. if (!initiated)
  55. {
  56. Debug.LogError("Trying to update an uninitiated Navigator.");
  57. return;
  58. }
  59. switch (state)
  60. {
  61. // When seeking path
  62. case State.Seeking:
  63. normalizedDeltaPosition = Vector3.zero;
  64. if (path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete)
  65. {
  66. corners = path.corners;
  67. cornerIndex = 0;
  68. if (corners.Length == 0)
  69. {
  70. Debug.LogWarning("Zero Corner Path", transform);
  71. Stop();
  72. }
  73. else
  74. {
  75. state = State.OnPath;
  76. }
  77. }
  78. if (path.status == UnityEngine.AI.NavMeshPathStatus.PathPartial)
  79. {
  80. Debug.LogWarning("Path Partial", transform);
  81. }
  82. if (path.status == UnityEngine.AI.NavMeshPathStatus.PathInvalid)
  83. {
  84. Debug.LogWarning("Path Invalid", transform);
  85. }
  86. break;
  87. // When already on path
  88. case State.OnPath:
  89. if (activeTargetSeeking && Time.time > nextPathTime && HorDistance(targetPosition, lastTargetPosition) > recalculateOnPathDistance)
  90. {
  91. CalculatePath(targetPosition);
  92. break;
  93. }
  94. if (cornerIndex < corners.Length)
  95. {
  96. Vector3 d = corners[cornerIndex] - transform.position;
  97. d.y = 0f;
  98. float mag = d.magnitude;
  99. if (mag > 0f) normalizedDeltaPosition = (d / d.magnitude);
  100. else normalizedDeltaPosition = Vector3.zero;
  101. if (mag < cornerRadius)
  102. {
  103. cornerIndex++;
  104. if (cornerIndex >= corners.Length) Stop();
  105. }
  106. }
  107. break;
  108. // Not on path, not seeking
  109. case State.Idle:
  110. if (activeTargetSeeking && Time.time > nextPathTime) CalculatePath(targetPosition);
  111. break;
  112. }
  113. }
  114. private void CalculatePath(Vector3 targetPosition)
  115. {
  116. if (Find(targetPosition))
  117. {
  118. lastTargetPosition = targetPosition;
  119. state = State.Seeking;
  120. }
  121. else
  122. {
  123. Stop();
  124. }
  125. nextPathTime = Time.time + nextPathInterval;
  126. }
  127. private bool Find(Vector3 targetPosition)
  128. {
  129. if (HorDistance(transform.position, targetPosition) < cornerRadius * 2f) return false;
  130. //if (HorDistance(targetPosition, lastTargetPosition) < recalculateBadTargetDistance) return false;
  131. if (UnityEngine.AI.NavMesh.CalculatePath(transform.position, targetPosition, UnityEngine.AI.NavMesh.AllAreas, path))
  132. {
  133. return true;
  134. }
  135. else
  136. {
  137. UnityEngine.AI.NavMeshHit hit = new UnityEngine.AI.NavMeshHit();
  138. if (UnityEngine.AI.NavMesh.SamplePosition(targetPosition, out hit, maxSampleDistance, UnityEngine.AI.NavMesh.AllAreas))
  139. {
  140. if (UnityEngine.AI.NavMesh.CalculatePath(transform.position, hit.position, UnityEngine.AI.NavMesh.AllAreas, path))
  141. {
  142. return true;
  143. }
  144. }
  145. }
  146. return false;
  147. }
  148. private void Stop()
  149. {
  150. state = State.Idle;
  151. normalizedDeltaPosition = Vector3.zero;
  152. }
  153. private float HorDistance(Vector3 p1, Vector3 p2)
  154. {
  155. return Vector2.Distance(new Vector2(p1.x, p1.z), new Vector2(p2.x, p2.z));
  156. }
  157. public void Visualize()
  158. {
  159. if (state == State.Idle) Gizmos.color = Color.gray;
  160. if (state == State.Seeking) Gizmos.color = Color.red;
  161. if (state == State.OnPath) Gizmos.color = Color.green;
  162. if (corners.Length > 0 && state == State.OnPath && cornerIndex == 0)
  163. {
  164. Gizmos.DrawLine(transform.position, corners[0]);
  165. }
  166. for (int i = 0; i < corners.Length; i++)
  167. {
  168. Gizmos.DrawSphere(corners[i], 0.1f);
  169. }
  170. if (corners.Length > 1)
  171. {
  172. for (int i = 0; i < corners.Length - 1; i++)
  173. {
  174. Gizmos.DrawLine(corners[i], corners[i + 1]);
  175. }
  176. }
  177. Gizmos.color = Color.white;
  178. }
  179. }
  180. }