AIPath.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace Pathfinding {
  5. using Pathfinding.RVO;
  6. using Pathfinding.Util;
  7. /// <summary>
  8. /// AI for following paths.
  9. /// This AI is the default movement script which comes with the A* Pathfinding Project.
  10. /// It is in no way required by the rest of the system, so feel free to write your own. But I hope this script will make it easier
  11. /// to set up movement for the characters in your game.
  12. /// This script works well for many types of units, but if you need the highest performance (for example if you are moving hundreds of characters) you
  13. /// may want to customize this script or write a custom movement script to be able to optimize it specifically for your game.
  14. ///
  15. /// This script will try to move to a given <see cref="destination"/>. At <see cref="repathRate regular"/>, the path to the destination will be recalculated.
  16. /// If you want to make the AI to follow a particular object you can attach the <see cref="Pathfinding.AIDestinationSetter"/> component.
  17. /// Take a look at the getstarted (view in online documentation for working links) tutorial for more instructions on how to configure this script.
  18. ///
  19. /// Here is a video of this script being used move an agent around (technically it uses the <see cref="Pathfinding.Examples.MineBotAI"/> script that inherits from this one but adds a bit of animation support for the example scenes):
  20. /// [Open online documentation to see videos]
  21. ///
  22. /// \section variables Quick overview of the variables
  23. /// In the inspector in Unity, you will see a bunch of variables. You can view detailed information further down, but here's a quick overview.
  24. ///
  25. /// The <see cref="repathRate"/> determines how often it will search for new paths, if you have fast moving targets, you might want to set it to a lower value.
  26. /// The <see cref="destination"/> field is where the AI will try to move, it can be a point on the ground where the player has clicked in an RTS for example.
  27. /// Or it can be the player object in a zombie game.
  28. /// The <see cref="maxSpeed"/> is self-explanatory, as is <see cref="rotationSpeed"/>. however <see cref="slowdownDistance"/> might require some explanation:
  29. /// It is the approximate distance from the target where the AI will start to slow down. Setting it to a large value will make the AI slow down very gradually.
  30. /// <see cref="pickNextWaypointDist"/> determines the distance to the point the AI will move to (see image below).
  31. ///
  32. /// Below is an image illustrating several variables that are exposed by this class (<see cref="pickNextWaypointDist"/>, <see cref="steeringTarget"/>, <see cref="desiredVelocity)"/>
  33. /// [Open online documentation to see images]
  34. ///
  35. /// This script has many movement fallbacks.
  36. /// If it finds an RVOController attached to the same GameObject as this component, it will use that. If it finds a character controller it will also use that.
  37. /// If it finds a rigidbody it will use that. Lastly it will fall back to simply modifying Transform.position which is guaranteed to always work and is also the most performant option.
  38. ///
  39. /// \section how-aipath-works How it works
  40. /// In this section I'm going to go over how this script is structured and how information flows.
  41. /// This is useful if you want to make changes to this script or if you just want to understand how it works a bit more deeply.
  42. /// However you do not need to read this section if you are just going to use the script as-is.
  43. ///
  44. /// This script inherits from the <see cref="AIBase"/> class. The movement happens either in Unity's standard <see cref="Update"/> or <see cref="FixedUpdate"/> method.
  45. /// They are both defined in the AIBase class. Which one is actually used depends on if a rigidbody is used for movement or not.
  46. /// Rigidbody movement has to be done inside the FixedUpdate method while otherwise it is better to do it in Update.
  47. ///
  48. /// From there a call is made to the <see cref="MovementUpdate"/> method (which in turn calls <see cref="MovementUpdateInternal)"/>.
  49. /// This method contains the main bulk of the code and calculates how the AI *wants* to move. However it doesn't do any movement itself.
  50. /// Instead it returns the position and rotation it wants the AI to move to have at the end of the frame.
  51. /// The <see cref="Update"/> (or <see cref="FixedUpdate)"/> method then passes these values to the <see cref="FinalizeMovement"/> method which is responsible for actually moving the character.
  52. /// That method also handles things like making sure the AI doesn't fall through the ground using raycasting.
  53. ///
  54. /// The AI recalculates its path regularly. This happens in the Update method which checks <see cref="shouldRecalculatePath"/> and if that returns true it will call <see cref="SearchPath"/>.
  55. /// The <see cref="SearchPath"/> method will prepare a path request and send it to the <see cref="Pathfinding.Seeker"/> component which should be attached to the same GameObject as this script.
  56. /// Since this script will when waking up register to the <see cref="Pathfinding.Seeker.pathCallback"/> delegate this script will be notified every time a new path is calculated by the <see cref="OnPathComplete"/> method being called.
  57. /// It may take one or sometimes multiple frames for the path to be calculated, but finally the <see cref="OnPathComplete"/> method will be called and the current path that the AI is following will be replaced.
  58. /// </summary>
  59. [AddComponentMenu("Pathfinding/AI/AIPath (2D,3D)")]
  60. public partial class AIPath : AIBase, IAstarAI {
  61. /// <summary>
  62. /// How quickly the agent accelerates.
  63. /// Positive values represent an acceleration in world units per second squared.
  64. /// Negative values are interpreted as an inverse time of how long it should take for the agent to reach its max speed.
  65. /// For example if it should take roughly 0.4 seconds for the agent to reach its max speed then this field should be set to -1/0.4 = -2.5.
  66. /// For a negative value the final acceleration will be: -acceleration*maxSpeed.
  67. /// This behaviour exists mostly for compatibility reasons.
  68. ///
  69. /// In the Unity inspector there are two modes: Default and Custom. In the Default mode this field is set to -2.5 which means that it takes about 0.4 seconds for the agent to reach its top speed.
  70. /// In the Custom mode you can set the acceleration to any positive value.
  71. /// </summary>
  72. public float maxAcceleration = -2.5f;
  73. /// <summary>
  74. /// Rotation speed in degrees per second.
  75. /// Rotation is calculated using Quaternion.RotateTowards. This variable represents the rotation speed in degrees per second.
  76. /// The higher it is, the faster the character will be able to rotate.
  77. /// </summary>
  78. [UnityEngine.Serialization.FormerlySerializedAs("turningSpeed")]
  79. public float rotationSpeed = 360;
  80. /// <summary>Distance from the end of the path where the AI will start to slow down</summary>
  81. public float slowdownDistance = 0.6F;
  82. /// <summary>
  83. /// How far the AI looks ahead along the path to determine the point it moves to.
  84. /// In world units.
  85. /// If you enable the <see cref="alwaysDrawGizmos"/> toggle this value will be visualized in the scene view as a blue circle around the agent.
  86. /// [Open online documentation to see images]
  87. ///
  88. /// Here are a few example videos showing some typical outcomes with good values as well as how it looks when this value is too low and too high.
  89. /// <table>
  90. /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-danger">Too low</span><br/></verbatim>\endxmlonly A too low value and a too low acceleration will result in the agent overshooting a lot and not managing to follow the path well.</td></tr>
  91. /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-warning">Ok</span><br/></verbatim>\endxmlonly A low value but a high acceleration works decently to make the AI follow the path more closely. Note that the <see cref="Pathfinding.AILerp"/> component is better suited if you want the agent to follow the path without any deviations.</td></tr>
  92. /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-success">Ok</span><br/></verbatim>\endxmlonly A reasonable value in this example.</td></tr>
  93. /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-success">Ok</span><br/></verbatim>\endxmlonly A reasonable value in this example, but the path is followed slightly more loosely than in the previous video.</td></tr>
  94. /// <tr><td>[Open online documentation to see videos]</td><td>\xmlonly <verbatim><span class="label label-danger">Too high</span><br/></verbatim>\endxmlonly A too high value will make the agent follow the path too loosely and may cause it to try to move through obstacles.</td></tr>
  95. /// </table>
  96. /// </summary>
  97. public float pickNextWaypointDist = 2;
  98. /// <summary>
  99. /// Distance to the end point to consider the end of path to be reached.
  100. /// When the end is within this distance then <see cref="OnTargetReached"/> will be called and <see cref="reachedEndOfPath"/> will return true.
  101. /// </summary>
  102. public float endReachedDistance = 0.2F;
  103. /// <summary>Draws detailed gizmos constantly in the scene view instead of only when the agent is selected and settings are being modified</summary>
  104. public bool alwaysDrawGizmos;
  105. /// <summary>
  106. /// Slow down when not facing the target direction.
  107. /// Incurs at a small performance overhead.
  108. /// </summary>
  109. public bool slowWhenNotFacingTarget = true;
  110. /// <summary>
  111. /// What to do when within <see cref="endReachedDistance"/> units from the destination.
  112. /// The character can either stop immediately when it comes within that distance, which is useful for e.g archers
  113. /// or other ranged units that want to fire on a target. Or the character can continue to try to reach the exact
  114. /// destination point and come to a full stop there. This is useful if you want the character to reach the exact
  115. /// point that you specified.
  116. ///
  117. /// Note: <see cref="reachedEndOfPath"/> will become true when the character is within <see cref="endReachedDistance"/> units from the destination
  118. /// regardless of what this field is set to.
  119. /// </summary>
  120. public CloseToDestinationMode whenCloseToDestination = CloseToDestinationMode.Stop;
  121. /// <summary>
  122. /// Ensure that the character is always on the traversable surface of the navmesh.
  123. /// When this option is enabled a <see cref="AstarPath.GetNearest"/> query will be done every frame to find the closest node that the agent can walk on
  124. /// and if the agent is not inside that node, then the agent will be moved to it.
  125. ///
  126. /// This is especially useful together with local avoidance in order to avoid agents pushing each other into walls.
  127. /// See: local-avoidance (view in online documentation for working links) for more info about this.
  128. ///
  129. /// This option also integrates with local avoidance so that if the agent is say forced into a wall by other agents the local avoidance
  130. /// system will be informed about that wall and can take that into account.
  131. ///
  132. /// Enabling this has some performance impact depending on the graph type (pretty fast for grid graphs, slightly slower for navmesh/recast graphs).
  133. /// If you are using a navmesh/recast graph you may want to switch to the <see cref="Pathfinding.RichAI"/> movement script which is specifically written for navmesh/recast graphs and
  134. /// does this kind of clamping out of the box. In many cases it can also follow the path more smoothly around sharp bends in the path.
  135. ///
  136. /// It is not recommended that you use this option together with the funnel modifier on grid graphs because the funnel modifier will make the path
  137. /// go very close to the border of the graph and this script has a tendency to try to cut corners a bit. This may cause it to try to go slightly outside the
  138. /// traversable surface near corners and that will look bad if this option is enabled.
  139. ///
  140. /// Warning: This option makes no sense to use on point graphs because point graphs do not have a surface.
  141. /// Enabling this option when using a point graph will lead to the agent being snapped to the closest node every frame which is likely not what you want.
  142. ///
  143. /// Below you can see an image where several agents using local avoidance were ordered to go to the same point in a corner.
  144. /// When not constraining the agents to the graph they are easily pushed inside obstacles.
  145. /// [Open online documentation to see images]
  146. /// </summary>
  147. public bool constrainInsideGraph = false;
  148. /// <summary>Current path which is followed</summary>
  149. protected Path path;
  150. /// <summary>Helper which calculates points along the current path</summary>
  151. protected PathInterpolator interpolator = new PathInterpolator();
  152. #region IAstarAI implementation
  153. /// <summary>\copydoc Pathfinding::IAstarAI::Teleport</summary>
  154. public override void Teleport (Vector3 newPosition, bool clearPath = true) {
  155. if (clearPath) interpolator.SetPath(null);
  156. reachedEndOfPath = false;
  157. base.Teleport(newPosition, clearPath);
  158. }
  159. /// <summary>\copydoc Pathfinding::IAstarAI::remainingDistance</summary>
  160. public float remainingDistance {
  161. get {
  162. return interpolator.valid ? interpolator.remainingDistance + movementPlane.ToPlane(interpolator.position - position).magnitude : float.PositiveInfinity;
  163. }
  164. }
  165. /// <summary>\copydoc Pathfinding::IAstarAI::reachedDestination</summary>
  166. public bool reachedDestination {
  167. get {
  168. if (!reachedEndOfPath) return false;
  169. if (remainingDistance + movementPlane.ToPlane(destination - interpolator.endPoint).magnitude > endReachedDistance) return false;
  170. // Don't do height checks in 2D mode
  171. if (orientation != OrientationMode.YAxisForward) {
  172. // Check if the destination is above the head of the character or far below the feet of it
  173. float yDifference;
  174. movementPlane.ToPlane(destination - position, out yDifference);
  175. var h = tr.localScale.y * height;
  176. if (yDifference > h || yDifference < -h*0.5) return false;
  177. }
  178. return true;
  179. }
  180. }
  181. /// <summary>\copydoc Pathfinding::IAstarAI::reachedEndOfPath</summary>
  182. public bool reachedEndOfPath { get; protected set; }
  183. /// <summary>\copydoc Pathfinding::IAstarAI::hasPath</summary>
  184. public bool hasPath {
  185. get {
  186. return interpolator.valid;
  187. }
  188. }
  189. /// <summary>\copydoc Pathfinding::IAstarAI::pathPending</summary>
  190. public bool pathPending {
  191. get {
  192. return waitingForPathCalculation;
  193. }
  194. }
  195. /// <summary>\copydoc Pathfinding::IAstarAI::steeringTarget</summary>
  196. public Vector3 steeringTarget {
  197. get {
  198. return interpolator.valid ? interpolator.position : position;
  199. }
  200. }
  201. /// <summary>\copydoc Pathfinding::IAstarAI::radius</summary>
  202. float IAstarAI.radius { get { return radius; } set { radius = value; } }
  203. /// <summary>\copydoc Pathfinding::IAstarAI::height</summary>
  204. float IAstarAI.height { get { return height; } set { height = value; } }
  205. /// <summary>\copydoc Pathfinding::IAstarAI::maxSpeed</summary>
  206. float IAstarAI.maxSpeed { get { return maxSpeed; } set { maxSpeed = value; } }
  207. /// <summary>\copydoc Pathfinding::IAstarAI::canSearch</summary>
  208. bool IAstarAI.canSearch { get { return canSearch; } set { canSearch = value; } }
  209. /// <summary>\copydoc Pathfinding::IAstarAI::canMove</summary>
  210. bool IAstarAI.canMove { get { return canMove; } set { canMove = value; } }
  211. #endregion
  212. protected override void OnDisable () {
  213. base.OnDisable();
  214. // Release current path so that it can be pooled
  215. if (path != null) path.Release(this);
  216. path = null;
  217. interpolator.SetPath(null);
  218. }
  219. /// <summary>
  220. /// The end of the path has been reached.
  221. /// If you want custom logic for when the AI has reached it's destination add it here. You can
  222. /// also create a new script which inherits from this one and override the function in that script.
  223. ///
  224. /// This method will be called again if a new path is calculated as the destination may have changed.
  225. /// So when the agent is close to the destination this method will typically be called every <see cref="repathRate"/> seconds.
  226. /// </summary>
  227. public virtual void OnTargetReached () {
  228. }
  229. /// <summary>
  230. /// Called when a requested path has been calculated.
  231. /// A path is first requested by <see cref="UpdatePath"/>, it is then calculated, probably in the same or the next frame.
  232. /// Finally it is returned to the seeker which forwards it to this function.
  233. /// </summary>
  234. protected override void OnPathComplete (Path newPath) {
  235. ABPath p = newPath as ABPath;
  236. if (p == null) throw new System.Exception("This function only handles ABPaths, do not use special path types");
  237. waitingForPathCalculation = false;
  238. // Increase the reference count on the new path.
  239. // This is used for object pooling to reduce allocations.
  240. p.Claim(this);
  241. // Path couldn't be calculated of some reason.
  242. // More info in p.errorLog (debug string)
  243. if (p.error) {
  244. p.Release(this);
  245. return;
  246. }
  247. // Release the previous path.
  248. if (path != null) path.Release(this);
  249. // Replace the old path
  250. path = p;
  251. // Make sure the path contains at least 2 points
  252. if (path.vectorPath.Count == 1) path.vectorPath.Add(path.vectorPath[0]);
  253. interpolator.SetPath(path.vectorPath);
  254. var graph = path.path.Count > 0 ? AstarData.GetGraph(path.path[0]) as ITransformedGraph : null;
  255. movementPlane = graph != null ? graph.transform : (orientation == OrientationMode.YAxisForward ? new GraphTransform(Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(-90, 270, 90), Vector3.one)) : GraphTransform.identityTransform);
  256. // Reset some variables
  257. reachedEndOfPath = false;
  258. // Simulate movement from the point where the path was requested
  259. // to where we are right now. This reduces the risk that the agent
  260. // gets confused because the first point in the path is far away
  261. // from the current position (possibly behind it which could cause
  262. // the agent to turn around, and that looks pretty bad).
  263. interpolator.MoveToLocallyClosestPoint((GetFeetPosition() + p.originalStartPoint) * 0.5f);
  264. interpolator.MoveToLocallyClosestPoint(GetFeetPosition());
  265. // Update which point we are moving towards.
  266. // Note that we need to do this here because otherwise the remainingDistance field might be incorrect for 1 frame.
  267. // (due to interpolator.remainingDistance being incorrect).
  268. interpolator.MoveToCircleIntersection2D(position, pickNextWaypointDist, movementPlane);
  269. var distanceToEnd = remainingDistance;
  270. if (distanceToEnd <= endReachedDistance) {
  271. reachedEndOfPath = true;
  272. OnTargetReached();
  273. }
  274. }
  275. /// <summary>Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not</summary>
  276. protected override void MovementUpdateInternal (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) {
  277. float currentAcceleration = maxAcceleration;
  278. // If negative, calculate the acceleration from the max speed
  279. if (currentAcceleration < 0) currentAcceleration *= -maxSpeed;
  280. if (updatePosition) {
  281. // Get our current position. We read from transform.position as few times as possible as it is relatively slow
  282. // (at least compared to a local variable)
  283. simulatedPosition = tr.position;
  284. }
  285. if (updateRotation) simulatedRotation = tr.rotation;
  286. var currentPosition = simulatedPosition;
  287. // Update which point we are moving towards
  288. interpolator.MoveToCircleIntersection2D(currentPosition, pickNextWaypointDist, movementPlane);
  289. var dir = movementPlane.ToPlane(steeringTarget - currentPosition);
  290. // Calculate the distance to the end of the path
  291. float distanceToEnd = dir.magnitude + Mathf.Max(0, interpolator.remainingDistance);
  292. // Check if we have reached the target
  293. var prevTargetReached = reachedEndOfPath;
  294. reachedEndOfPath = distanceToEnd <= endReachedDistance && interpolator.valid;
  295. if (!prevTargetReached && reachedEndOfPath) OnTargetReached();
  296. float slowdown;
  297. // Normalized direction of where the agent is looking
  298. var forwards = movementPlane.ToPlane(simulatedRotation * (orientation == OrientationMode.YAxisForward ? Vector3.up : Vector3.forward));
  299. // Check if we have a valid path to follow and some other script has not stopped the character
  300. if (interpolator.valid && !isStopped) {
  301. // How fast to move depending on the distance to the destination.
  302. // Move slower as the character gets closer to the destination.
  303. // This is always a value between 0 and 1.
  304. slowdown = distanceToEnd < slowdownDistance ? Mathf.Sqrt(distanceToEnd / slowdownDistance) : 1;
  305. if (reachedEndOfPath && whenCloseToDestination == CloseToDestinationMode.Stop) {
  306. // Slow down as quickly as possible
  307. velocity2D -= Vector2.ClampMagnitude(velocity2D, currentAcceleration * deltaTime);
  308. } else {
  309. velocity2D += MovementUtilities.CalculateAccelerationToReachPoint(dir, dir.normalized*maxSpeed, velocity2D, currentAcceleration, rotationSpeed, maxSpeed, forwards) * deltaTime;
  310. }
  311. } else {
  312. slowdown = 1;
  313. // Slow down as quickly as possible
  314. velocity2D -= Vector2.ClampMagnitude(velocity2D, currentAcceleration * deltaTime);
  315. }
  316. velocity2D = MovementUtilities.ClampVelocity(velocity2D, maxSpeed, slowdown, slowWhenNotFacingTarget && enableRotation, forwards);
  317. ApplyGravity(deltaTime);
  318. // Set how much the agent wants to move during this frame
  319. var delta2D = lastDeltaPosition = CalculateDeltaToMoveThisFrame(movementPlane.ToPlane(currentPosition), distanceToEnd, deltaTime);
  320. nextPosition = currentPosition + movementPlane.ToWorld(delta2D, verticalVelocity * lastDeltaTime);
  321. CalculateNextRotation(slowdown, out nextRotation);
  322. }
  323. protected virtual void CalculateNextRotation (float slowdown, out Quaternion nextRotation) {
  324. if (lastDeltaTime > 0.00001f && enableRotation) {
  325. Vector2 desiredRotationDirection;
  326. desiredRotationDirection = velocity2D;
  327. // Rotate towards the direction we are moving in.
  328. // Don't rotate when we are very close to the target.
  329. var currentRotationSpeed = rotationSpeed * Mathf.Max(0, (slowdown - 0.3f) / 0.7f);
  330. nextRotation = SimulateRotationTowards(desiredRotationDirection, currentRotationSpeed * lastDeltaTime);
  331. } else {
  332. // TODO: simulatedRotation
  333. nextRotation = rotation;
  334. }
  335. }
  336. static NNConstraint cachedNNConstraint = NNConstraint.Default;
  337. protected override Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged) {
  338. if (constrainInsideGraph) {
  339. cachedNNConstraint.tags = seeker.traversableTags;
  340. cachedNNConstraint.graphMask = seeker.graphMask;
  341. cachedNNConstraint.distanceXZ = true;
  342. var clampedPosition = AstarPath.active.GetNearest(position, cachedNNConstraint).position;
  343. // We cannot simply check for equality because some precision may be lost
  344. // if any coordinate transformations are used.
  345. var difference = movementPlane.ToPlane(clampedPosition - position);
  346. float sqrDifference = difference.sqrMagnitude;
  347. if (sqrDifference > 0.001f*0.001f) {
  348. // The agent was outside the navmesh. Remove that component of the velocity
  349. // so that the velocity only goes along the direction of the wall, not into it
  350. velocity2D -= difference * Vector2.Dot(difference, velocity2D) / sqrDifference;
  351. positionChanged = true;
  352. // Return the new position, but ignore any changes in the y coordinate from the ClampToNavmesh method as the y coordinates in the navmesh are rarely very accurate
  353. return position + movementPlane.ToWorld(difference);
  354. }
  355. }
  356. positionChanged = false;
  357. return position;
  358. }
  359. #if UNITY_EDITOR
  360. [System.NonSerialized]
  361. int gizmoHash = 0;
  362. [System.NonSerialized]
  363. float lastChangedTime = float.NegativeInfinity;
  364. protected static readonly Color GizmoColor = new Color(46.0f/255, 104.0f/255, 201.0f/255);
  365. protected override void OnDrawGizmos () {
  366. base.OnDrawGizmos();
  367. if (alwaysDrawGizmos) OnDrawGizmosInternal();
  368. }
  369. protected override void OnDrawGizmosSelected () {
  370. base.OnDrawGizmosSelected();
  371. if (!alwaysDrawGizmos) OnDrawGizmosInternal();
  372. }
  373. void OnDrawGizmosInternal () {
  374. var newGizmoHash = pickNextWaypointDist.GetHashCode() ^ slowdownDistance.GetHashCode() ^ endReachedDistance.GetHashCode();
  375. if (newGizmoHash != gizmoHash && gizmoHash != 0) lastChangedTime = Time.realtimeSinceStartup;
  376. gizmoHash = newGizmoHash;
  377. float alpha = alwaysDrawGizmos ? 1 : Mathf.SmoothStep(1, 0, (Time.realtimeSinceStartup - lastChangedTime - 5f)/0.5f) * (UnityEditor.Selection.gameObjects.Length == 1 ? 1 : 0);
  378. if (alpha > 0) {
  379. // Make sure the scene view is repainted while the gizmos are visible
  380. if (!alwaysDrawGizmos) UnityEditor.SceneView.RepaintAll();
  381. Draw.Gizmos.Line(position, steeringTarget, GizmoColor * new Color(1, 1, 1, alpha));
  382. Gizmos.matrix = Matrix4x4.TRS(position, transform.rotation * (orientation == OrientationMode.YAxisForward ? Quaternion.Euler(-90, 0, 0) : Quaternion.identity), Vector3.one);
  383. Draw.Gizmos.CircleXZ(Vector3.zero, pickNextWaypointDist, GizmoColor * new Color(1, 1, 1, alpha));
  384. Draw.Gizmos.CircleXZ(Vector3.zero, slowdownDistance, Color.Lerp(GizmoColor, Color.red, 0.5f) * new Color(1, 1, 1, alpha));
  385. Draw.Gizmos.CircleXZ(Vector3.zero, endReachedDistance, Color.Lerp(GizmoColor, Color.red, 0.8f) * new Color(1, 1, 1, alpha));
  386. }
  387. }
  388. #endif
  389. protected override int OnUpgradeSerializedData (int version, bool unityThread) {
  390. base.OnUpgradeSerializedData(version, unityThread);
  391. // Approximately convert from a damping value to a degrees per second value.
  392. if (version < 1) rotationSpeed *= 90;
  393. return 2;
  394. }
  395. }
  396. }