A* Pathfinding Project  4.1.6
The A* Pathfinding Project for Unity 3D
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Events Macros Groups Pages
LegacyAIPath Class Reference

AI for following paths. More...

Detailed Description

AI for following paths.

This AI is the default movement script which comes with the A* Pathfinding Project. 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 to set up movement for the characters in your game. This script is not written for high performance, so I do not recommend using it for large groups of units.

This script will try to follow a target transform, in regular intervals, the path to that target will be recalculated. It will on FixedUpdate try to move towards the next point in the path. However it will only move in the forward direction, but it will rotate around it's Y-axis to make it reach the target.

Quick overview of the variables

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.
The 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.
The target variable 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. Or it can be the player object in a zombie game.
The speed is self-explanatory, so is turningSpeed, however slowdownDistance might require some explanation. It is the approximate distance from the target where the AI will start to slow down. Note that this doesn't only affect the end point of the path but also any intermediate points, so be sure to set forwardLook and pickNextWaypointDist to a higher value than this.
pickNextWaypointDist is simply determines within what range it will switch to target the next waypoint in the path.
forwardLook will try to calculate an interpolated target point on the current segment in the path so that it has a distance of forwardLook from the AI
Below is an image illustrating several variables as well as some internal ones, but which are relevant for understanding how it works. Note that the forwardLook range will not match up exactly with the target point practically, even though that's the goal.

This script has many movement fallbacks. If it finds a NavmeshController, it will use that, otherwise it will look for a character controller, then for a rigidbody and if it hasn't been able to find any it will use Transform.Translate which is guaranteed to always work.

Deprecated:
Use the AIPath class instead. This class only exists for compatibility reasons.

Public Member Functions

override void OnPathComplete (Path _p)
 Called when a requested path has finished calculation.
 
- Public Member Functions inherited from AIPath
Vector3 CalculateVelocity (Vector3 position)
 Current desired velocity of the agent (excluding physics and local avoidance but it includes gravity).
 
virtual void OnTargetReached ()
 The end of the path has been reached.
 
override void Teleport (Vector3 newPosition, bool clearPath=true)
 Instantly move the agent to a new position.
 
- Public Member Functions inherited from AIBase
virtual void FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation)
 Moves the agent to a position.
 
virtual Vector3 GetFeetPosition ()
 Position of the base of the character.
 
virtual void Move (Vector3 deltaPosition)
 Move the agent.
 
void MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation)
 Calculate how the character wants to move during this frame.
 
virtual void SearchPath ()
 Recalculate the current path.
 
Quaternion SimulateRotationTowards (Vector3 direction, float maxDegrees)
 Simulates rotating the agent towards the specified direction and returns the new rotation.
 
- Public Member Functions inherited from IAstarAI
void FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation)
 Move the agent.
 
void Move (Vector3 deltaPosition)
 Move the agent.
 
void MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation)
 Calculate how the character wants to move during this frame.
 
void SearchPath ()
 Recalculate the current path.
 
void Teleport (Vector3 newPosition, bool clearPath=true)
 Instantly move the agent to a new position.
 

Public Attributes

bool closestOnPathCheck = true
 Do a closest point on path check when receiving path callback.
 
float forwardLook = 1
 Target point is Interpolated on the current segment in the path so that it has a distance of forwardLook from the AI.
 
- Public Attributes inherited from AIPath
bool alwaysDrawGizmos
 Draws detailed gizmos constantly in the scene view instead of only when the agent is selected and settings are being modified.
 
float endReachedDistance = 0.2F
 Distance to the end point to consider the end of path to be reached.
 
float pickNextWaypointDist = 2
 Determines within what range it will switch to target the next waypoint in the path.
 
float rotationSpeed = 360
 Rotation speed.
 
float slowdownDistance = 0.6F
 Distance from the target point where the AI will start to slow down.
 
bool slowWhenNotFacingTarget = true
 Slow down when not facing the target direction.
 
CloseToDestinationMode whenCloseToDestination = CloseToDestinationMode.Stop
 What to do when within endReachedDistance units from the destination.
 
- Public Attributes inherited from AIBase
bool canMove = true
 Enables or disables movement completely.
 
bool canSearch = true
 Enables or disables recalculating the path at regular intervals.
 
float centerOffset = 1
 Offset along the Y coordinate for the ground raycast start position.
 
Vector3 gravity = new Vector3(float.NaN, float.NaN, float.NaN)
 Gravity to use.
 
LayerMask groundMask = -1
 Layer mask to use for ground placement.
 
float maxSpeed = 1
 Max speed in world units per second.
 
IMovementPlane movementPlane = GraphTransform.identityTransform
 Plane which this agent is moving in.
 
float repathRate = 0.5f
 Determines how often the agent will search for new paths (in seconds).
 
bool rotationIn2D = false
 If true, the forward axis of the character will be along the Y axis instead of the Z axis.
 
bool updatePosition = true
 Determines if the character's position should be coupled to the Transform's position.
 
bool updateRotation = true
 Determines if the character's rotation should be coupled to the Transform's rotation.
 

Protected Member Functions

override void Awake ()
 
Vector3 CalculateTargetPoint (Vector3 p, Vector3 a, Vector3 b)
 Calculates target point from the current line segment.
 
new Vector3 CalculateVelocity (Vector3 currentPosition)
 Calculates desired velocity.
 
void RotateTowards (Vector3 dir)
 Rotates in the specified direction.
 
override void Update ()
 Called every frame.
 
float XZSqrMagnitude (Vector3 a, Vector3 b)
 
- Protected Member Functions inherited from AIPath
virtual void CalculateNextRotation (float slowdown, out Quaternion nextRotation)
 
override void MovementUpdateInternal (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation)
 Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not.
 
override void OnDisable ()
 
override int OnUpgradeSerializedData (int version, bool unityThread)
 Handle serialization backwards compatibility.
 
- Protected Member Functions inherited from AIBase
 AIBase ()
 
void ApplyGravity (float deltaTime)
 Accelerates the agent downwards.
 
Vector2 CalculateDeltaToMoveThisFrame (Vector2 position, float distanceToEndOfPath, float deltaTime)
 Calculates how far to move during a single frame.
 
virtual void CalculatePathRequestEndpoints (out Vector3 start, out Vector3 end)
 Outputs the start point and end point of the next automatic path request.
 
void CancelCurrentPathRequest ()
 
virtual Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged)
 Constrains the character's position to lie on the navmesh.
 
virtual void FindComponents ()
 
virtual void FixedUpdate ()
 Called every physics update.
 
virtual void OnDrawGizmos ()
 
virtual void OnDrawGizmosSelected ()
 
virtual void OnEnable ()
 Called when the component is enabled.
 
Vector3 RaycastPosition (Vector3 position, float lastElevation)
 Checks if the character is grounded and prevents ground penetration.
 
IEnumerator RepeatTrySearchPath ()
 Tries to search for a path every repathRate seconds.
 
Quaternion SimulateRotationTowards (Vector2 direction, float maxDegrees)
 Simulates rotating the agent towards the specified direction and returns the new rotation.
 
virtual void Start ()
 Starts searching for paths.
 
void UpdateVelocity ()
 

Protected Attributes

int currentWaypointIndex = 0
 Current index in the path which is current target.
 
Vector3 lastFoundWaypointPosition
 
float lastFoundWaypointTime = -9999
 
float minMoveScale = 0.05F
 
new Vector3 targetDirection
 Relative direction to where the AI is heading.
 
- Protected Attributes inherited from AIPath
PathInterpolator interpolator = new PathInterpolator()
 Helper which calculates points along the current path.
 
Path path
 Current path which is followed.
 
- Protected Attributes inherited from AIBase
CharacterController controller
 Cached CharacterController component.
 
Vector2 lastDeltaPosition
 Amount which the character wants or tried to move with during the last frame.
 
float lastDeltaTime
 Delta time used for movement during the last frame.
 
float lastRepath = float.NegativeInfinity
 Time when the last path request was started.
 
int prevFrame
 Last frame index when prevPosition1 was updated.
 
Vector3 prevPosition1
 Position of the character at the end of the last frame.
 
Vector3 prevPosition2
 Position of the character at the end of the frame before the last frame.
 
Rigidbody rigid
 Cached Rigidbody component.
 
Rigidbody2D rigid2D
 Cached Rigidbody component.
 
RVOController rvoController
 Cached RVOController component.
 
Seeker seeker
 Cached Seeker component.
 
Vector3 simulatedPosition
 Position of the agent.
 
Quaternion simulatedRotation
 Rotation of the agent.
 
Transform tr
 Cached Transform component.
 
Vector2 velocity2D
 Current desired velocity of the agent (does not include local avoidance and physics).
 
float verticalVelocity
 Velocity due to gravity.
 
bool waitingForPathCalculation = false
 Only when the previous path has been calculated should the script consider searching for a new path.
 

Additional Inherited Members

- Static Protected Attributes inherited from AIBase
static readonly Color GizmoColorRaycast = new Color(118.0f/255, 206.0f/255, 112.0f/255)
 
- Properties inherited from AIPath
bool IAstarAI. canMove [get, set]
 Enables or disables movement completely.
 
bool IAstarAI. canSearch [get, set]
 Enables or disables recalculating the path at regular intervals.
 
bool hasPath [get]
 True if this agent currently has a path that it follows.
 
float IAstarAI. maxSpeed [get, set]
 Max speed in world units per second.
 
bool pathPending [get]
 True if a path is currently being calculated.
 
float remainingDistance [get]
 Remaining distance along the current path to the end of the path.
 
float speed [get, set]
 Maximum speed in world units per second.
 
Vector3 steeringTarget [get]
 Point on the path which the agent is currently moving towards.
 
Vector3 targetDirection [get]
 Direction that the agent wants to move in (excluding physics and local avoidance).
 
bool TargetReached [get]
 True if the end of the path has been reached.
 
bool targetReached [get, set]
 True if the agent has reached the end of the current path.
 
float turningSpeed [get, set]
 Rotation speed.
 

Member Function Documentation

override void Awake ( )
protectedvirtual

Reimplemented from VersionedMonoBehaviour.

Vector3 CalculateTargetPoint ( Vector3  p,
Vector3  a,
Vector3  b 
)
protected

Calculates target point from the current line segment.

Parameters
pCurrent position
aLine segment start
bLine segment end The returned point will lie somewhere on the line segment.
See Also
forwardLook
Todo:
This function uses .magnitude quite a lot, can it be optimized?
new Vector3 CalculateVelocity ( Vector3  currentPosition)
protected

Calculates desired velocity.

Finds the target path segment and returns the forward direction, scaled with speed. A whole bunch of restrictions on the velocity is applied to make sure it doesn't overshoot, does not look too far ahead, and slows down when close to the target. /see speed /see endReachedDistance /see slowdownDistance /see CalculateTargetPoint /see targetPoint /see targetDirection /see currentWaypointIndex

override void OnPathComplete ( Path  _p)
virtual

Called when a requested path has finished calculation.

A path is first requested by SearchPath, it is then calculated, probably in the same or the next frame. Finally it is returned to the seeker which forwards it to this function.

Reimplemented from AIPath.

void RotateTowards ( Vector3  dir)
protected

Rotates in the specified direction.

Rotates around the Y-axis.

See Also
turningSpeed
override void Update ( )
protectedvirtual

Called every frame.

If no rigidbodies are used then all movement happens here.

Reimplemented from AIBase.

float XZSqrMagnitude ( Vector3  a,
Vector3  b 
)
protected

Member Data Documentation

bool closestOnPathCheck = true

Do a closest point on path check when receiving path callback.

Usually the AI has moved a bit between requesting the path, and getting it back, and there is usually a small gap between the AI and the closest node. If this option is enabled, it will simulate, when the path callback is received, movement between the closest node and the current AI position. This helps to reduce the moments when the AI just get a new path back, and thinks it ought to move backwards to the start of the new path even though it really should just proceed forward.

int currentWaypointIndex = 0
protected

Current index in the path which is current target.

float forwardLook = 1

Target point is Interpolated on the current segment in the path so that it has a distance of forwardLook from the AI.

See the detailed description of AIPath for an illustrative image

Vector3 lastFoundWaypointPosition
protected
float lastFoundWaypointTime = -9999
protected
float minMoveScale = 0.05F
protected
new Vector3 targetDirection
protected

Relative direction to where the AI is heading.

Filled in by CalculateVelocity


The documentation for this class was generated from the following file: