A* Pathfinding Project  4.1.7
The A* Pathfinding Project for Unity 3D
AIPath 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 works well for many types of units, but if you need the highest performance (for example if you are moving hundreds of characters) you may want to customize this script or write a custom movement script to be able to optimize it specifically for your game.

This script will try to follow a target transform. At regular intervals, the path to that target will be recalculated. It will in the Update method try to move towards the next point in the path. However it will only move in roughly forward direction (Z+ axis) of the character, but it will rotate around it's Y-axis to make it possible to reach the destination.

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 rotationSpeed, however slowdownDistance might require some explanation. It is the approximate distance from the target where the AI will start to slow down.
pickNextWaypointDist is simply determines within what range it will switch to target the next waypoint in the path.
Below is an image illustrating several variables as well as some internal ones, but which are relevant for understanding how it works.

Note
The image is slightly outdated, replace forwardLook with pickNextWaypointDist in the image and ignore the circle for pickNextWaypointDist.

This script has many movement fallbacks. If it finds an RVOController attached to the same GameObject as this component, it will use that. If it fins a character controller it will also use that. Lastly if will fall back to simply modifying Transform.position which is guaranteed to always work and is also the most performant option.

Public Member Functions

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

Public Attributes

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

Protected Member Functions

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. More...
 
override void OnDisable ()
 
override int OnUpgradeSerializedData (int version, bool unityThread)
 Handle serialization backwards compatibility. More...
 
virtual void UpdateMovementPlane ()
 
- Protected Member Functions inherited from AIBase
 AIBase ()
 
void ApplyGravity (float deltaTime)
 Accelerates the agent downwards. More...
 
Vector2 CalculateDeltaToMoveThisFrame (Vector2 position, float distanceToEndOfPath, float deltaTime)
 Calculates how far to move during a single frame. More...
 
virtual void CalculatePathRequestEndpoints (out Vector3 start, out Vector3 end)
 Outputs the start point and end point of the next automatic path request. More...
 
void CancelCurrentPathRequest ()
 
virtual Vector3 ClampToNavmesh (Vector3 position, out bool positionChanged)
 Constrains the character's position to lie on the navmesh. More...
 
virtual void FindComponents ()
 
virtual void FixedUpdate ()
 Called every physics update. More...
 
virtual void OnDrawGizmos ()
 
virtual void OnDrawGizmosSelected ()
 
virtual void OnEnable ()
 Called when the component is enabled. More...
 
Vector3 RaycastPosition (Vector3 position, float lastElevation)
 Checks if the character is grounded and prevents ground penetration. More...
 
IEnumerator RepeatTrySearchPath ()
 Tries to search for a path every repathRate seconds. More...
 
Quaternion SimulateRotationTowards (Vector2 direction, float maxDegrees)
 Simulates rotating the agent towards the specified direction and returns the new rotation. More...
 
virtual void Start ()
 Starts searching for paths. More...
 
virtual void Update ()
 Called every frame. More...
 
void UpdateVelocity ()
 
- Protected Member Functions inherited from VersionedMonoBehaviour
virtual void Awake ()
 

Protected Attributes

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

Properties

bool IAstarAI. canMove [get, set]
 Enables or disables movement completely. More...
 
bool IAstarAI. canSearch [get, set]
 Enables or disables recalculating the path at regular intervals. More...
 
bool hasPath [get]
 True if this agent currently has a path that it follows. More...
 
float IAstarAI. maxSpeed [get, set]
 Max speed in world units per second. More...
 
bool pathPending [get]
 True if a path is currently being calculated. More...
 
float remainingDistance [get]
 Remaining distance along the current path to the end of the path. More...
 
float speed [get, set]
 Maximum speed in world units per second. More...
 
Vector3 steeringTarget [get]
 Point on the path which the agent is currently moving towards. More...
 
Vector3 targetDirection [get]
 Direction that the agent wants to move in (excluding physics and local avoidance). More...
 
bool TargetReached [get]
 True if the end of the path has been reached. More...
 
bool targetReached [get, protected set]
 True if the agent has reached the end of the current path. More...
 
float turningSpeed [get, set]
 Rotation speed. More...
 
- Properties inherited from AIBase
Vector3 desiredVelocity [get]
 Velocity that this agent wants to move with. More...
 
Vector3 destination [get, set]
 Position in the world that this agent should move to. More...
 
bool isStopped [get, set]
 Gets or sets if the agent should stop moving. More...
 
System.Action onSearchPath [get, set]
 Called when the agent recalculates its path. More...
 
Vector3 position [get]
 Position of the agent. More...
 
Quaternion rotation [get]
 Rotation of the agent. More...
 
virtual bool shouldRecalculatePath [get]
 True if the path should be automatically recalculated as soon as possible. More...
 
Transform target [get, set]
 Target to move towards. More...
 
bool usingGravity [get, private set]
 Indicates if gravity is used during this frame. More...
 
Vector3 velocity [get]
 Actual velocity that the agent is moving with. More...
 
- Properties inherited from IAstarAI
bool canMove [get, set]
 Enables or disables movement completely. More...
 
bool canSearch [get, set]
 Enables or disables recalculating the path at regular intervals. More...
 
Vector3 desiredVelocity [get]
 Velocity that this agent wants to move with. More...
 
Vector3 destination [get, set]
 Position in the world that this agent should move to. More...
 
bool hasPath [get]
 True if this agent currently has a path that it follows. More...
 
bool isStopped [get, set]
 Gets or sets if the agent should stop moving. More...
 
float maxSpeed [get, set]
 Max speed in world units per second. More...
 
System.Action onSearchPath [get, set]
 Called when the agent recalculates its path. More...
 
bool pathPending [get]
 True if a path is currently being calculated. More...
 
Vector3 position [get]
 Position of the agent. More...
 
float remainingDistance [get]
 Remaining distance along the current path to the end of the path. More...
 
Quaternion rotation [get]
 Rotation of the agent. More...
 
Vector3 steeringTarget [get]
 Point on the path which the agent is currently moving towards. More...
 
bool targetReached [get]
 True if the agent has reached the end of the current path. More...
 
Vector3 velocity [get]
 Actual velocity that the agent is moving with. More...
 

Additional Inherited Members

- Static Protected Attributes inherited from AIBase
static readonly Color GizmoColorRaycast = new Color(118.0f/255, 206.0f/255, 112.0f/255)
 

Member Function Documentation

◆ CalculateNextRotation()

virtual void CalculateNextRotation ( float  slowdown,
out Quaternion  nextRotation 
)
protectedvirtual

◆ CalculateVelocity()

Vector3 CalculateVelocity ( Vector3  position)

Current desired velocity of the agent (excluding physics and local avoidance but it includes gravity).

Deprecated:
This method no longer calculates the velocity. Use the desiredVelocity property instead.

◆ MovementUpdateInternal()

override void MovementUpdateInternal ( float  deltaTime,
out Vector3  nextPosition,
out Quaternion  nextRotation 
)
protectedvirtual

Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not.

Implements AIBase.

◆ OnDisable()

override void OnDisable ( )
protectedvirtual

Reimplemented from AIBase.

◆ OnPathComplete()

override void OnPathComplete ( Path  newPath)
virtual

Called when a requested path has been calculated.

A path is first requested by #UpdatePath, 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.

Implements AIBase.

Reimplemented in LegacyAIPath.

◆ OnTargetReached()

virtual void OnTargetReached ( )
virtual

The end of the path has been reached.

If you want custom logic for when the AI has reached it's destination add it here. You can also create a new script which inherits from this one and override the function in that script.

This method will be called again if a new path is calculated as the destination may have changed. So when the agent is close to the destination this method will typically be called every repathRate seconds.

Reimplemented in MineBotAI.

◆ OnUpgradeSerializedData()

override int OnUpgradeSerializedData ( int  version,
bool  unityThread 
)
protectedvirtual

Handle serialization backwards compatibility.

Reimplemented from AIBase.

◆ Teleport()

override void Teleport ( Vector3  newPosition,
bool  clearPath = true 
)
virtual

Instantly move the agent to a new position.

This will trigger a path recalculation (if clearPath is true, which is the default) so if you want to teleport the agent and change its destination it is recommended that you set the destination before calling this method.

The current path will be cleared by default.

See also
Works similarly to Unity's NavmeshAgent.Warp.
SearchPath

Reimplemented from AIBase.

◆ UpdateMovementPlane()

virtual void UpdateMovementPlane ( )
protectedvirtual

Reimplemented in AIArbitrarySurface.

Member Data Documentation

◆ alwaysDrawGizmos

bool alwaysDrawGizmos

Draws detailed gizmos constantly in the scene view instead of only when the agent is selected and settings are being modified.

◆ endReachedDistance

float endReachedDistance = 0.2F

Distance to the end point to consider the end of path to be reached.

When the end is within this distance then OnTargetReached will be called and targetReached will return true.

◆ interpolator

PathInterpolator interpolator = new PathInterpolator()
protected

Helper which calculates points along the current path.

◆ path

Path path
protected

Current path which is followed.

◆ pickNextWaypointDist

float pickNextWaypointDist = 2

Determines within what range it will switch to target the next waypoint in the path.

◆ rotationSpeed

float rotationSpeed = 360

Rotation speed.

Rotation is calculated using Quaternion.RotateTowards. This variable represents the rotation speed in degrees per second. The higher it is, the faster the character will be able to rotate.

◆ slowdownDistance

float slowdownDistance = 0.6F

Distance from the end of the path where the AI will start to slow down.

◆ slowWhenNotFacingTarget

bool slowWhenNotFacingTarget = true

Slow down when not facing the target direction.

Incurs at a small performance overhead.

◆ whenCloseToDestination

What to do when within endReachedDistance units from the destination.

The character can either stop immediately when it comes within that distance, which is useful for e.g archers or other ranged units that want to fire on a target. Or the character can continue to try to reach the exact destination point and come to a full stop there. This is useful if you want the character to reach the exact point that you specified.

Note
targetReached will become true when the character is within endReachedDistance units from the destination regardless of what this field is set to.

Property Documentation

◆ canMove

bool IAstarAI. canMove
getsetprivate

Enables or disables movement completely.

If you want the agent to stand still, but still react to local avoidance and use gravity: use isStopped instead.

This is also useful if you want to have full control over when the movement calculations run. Take a look at MovementUpdate

See also
canSearch
isStopped

◆ canSearch

bool IAstarAI. canSearch
getsetprivate

Enables or disables recalculating the path at regular intervals.

Setting this to false does not stop any active path requests from being calculated or stop it from continuing to follow the current path.

Note that this only disables automatic path recalculations. If you call the SearchPath() method a path will still be calculated.

See also
canMove
isStopped

◆ hasPath

bool hasPath
get

True if this agent currently has a path that it follows.

◆ maxSpeed

float IAstarAI. maxSpeed
getsetprivate

Max speed in world units per second.

◆ pathPending

bool pathPending
get

True if a path is currently being calculated.

◆ remainingDistance

float remainingDistance
get

Remaining distance along the current path to the end of the path.

For the RichAI movement script this may not always be precisely known, especially when far away from the destination. In those cases an approximate distance will be returned.

If the agent does not currently have a path, then positive infinity will be returned.

◆ speed

float speed
getset

Maximum speed in world units per second.

Deprecated:
Use maxSpeed instead

◆ steeringTarget

Vector3 steeringTarget
get

Point on the path which the agent is currently moving towards.

This is usually a point a small distance ahead of the agent or the end of the path.

If the agent does not have a path at the moment, then the agent's current position will be returned.

◆ targetDirection

Vector3 targetDirection
get

Direction that the agent wants to move in (excluding physics and local avoidance).

Deprecated:
Only exists for compatibility reasons. Use desiredVelocity or steeringTarget instead instead.

◆ TargetReached

bool TargetReached
get

True if the end of the path has been reached.

Deprecated:
When unifying the interfaces for different movement scripts, this property has been renamed to targetReached (lowercase t)

◆ targetReached

bool targetReached
getprotected set

True if the agent has reached the end of the current path.

◆ turningSpeed

float turningSpeed
getset

Rotation speed.

Deprecated:
This field has been renamed to rotationSpeed and is now in degrees per second instead of a damping factor.

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