A* Pathfinding Project  4.1.9
The A* Pathfinding Project for Unity 3D
AIBase Class Referenceabstract

Base class for AIPath and RichAI. More...

Detailed Description

Base class for AIPath and RichAI.

This class holds various methods and fields that are common to both AIPath and RichAI.

See also
Pathfinding.AIPath
Pathfinding.RichAI
Pathfinding.IAstarAI (all movement scripts implement this interface)

Public Member Functions

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...
 
abstract void OnPathComplete (Path newPath)
 Called when a requested path has been calculated. 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...
 
virtual void Teleport (Vector3 newPosition, bool clearPath=true)
 Instantly move the agent to a new position. More...
 

Public Attributes

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

 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...
 
abstract 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...
 
virtual void OnDisable ()
 
virtual void OnDrawGizmos ()
 
virtual void OnDrawGizmosSelected ()
 
virtual void OnEnable ()
 Called when the component is enabled. More...
 
override int OnUpgradeSerializedData (int version, bool unityThread)
 Handle serialization backwards compatibility. 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

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...
 

Static Protected Attributes

static readonly Color GizmoColorRaycast = new Color(118.0f/255, 206.0f/255, 112.0f/255)
 

Properties

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...
 

Private Member Functions

void FinalizePosition (Vector3 nextPosition)
 
void FinalizeRotation (Quaternion nextRotation)
 
void Init ()
 

Private Attributes

Vector3 accumulatedMovementDelta = Vector3.zero
 Accumulated movement deltas from the Move method. More...
 
bool startHasRun = false
 True if the Start method has been executed. More...
 
Transform targetCompatibility
 

Constructor & Destructor Documentation

◆ AIBase()

AIBase ( )
protected

Member Function Documentation

◆ ApplyGravity()

void ApplyGravity ( float  deltaTime)
protected

Accelerates the agent downwards.

See also
verticalVelocity
gravity

◆ CalculateDeltaToMoveThisFrame()

Vector2 CalculateDeltaToMoveThisFrame ( Vector2  position,
float  distanceToEndOfPath,
float  deltaTime 
)
protected

Calculates how far to move during a single frame.

◆ CalculatePathRequestEndpoints()

virtual void CalculatePathRequestEndpoints ( out Vector3  start,
out Vector3  end 
)
protectedvirtual

Outputs the start point and end point of the next automatic path request.

This is a separate method to make it easy for subclasses to swap out the endpoints of path requests. For example the #LocalSpaceRichAI script which requires the endpoints to be transformed to graph space first.

Reimplemented in LocalSpaceRichAI.

◆ CancelCurrentPathRequest()

void CancelCurrentPathRequest ( )
protected

◆ ClampToNavmesh()

virtual Vector3 ClampToNavmesh ( Vector3  position,
out bool  positionChanged 
)
protectedvirtual

Constrains the character's position to lie on the navmesh.

Not all movement scripts have support for this.

Parameters
positionCurrent position of the character.
positionChangedTrue if the character's position was modified by this method.
Returns
New position of the character that has been clamped to the navmesh.

Reimplemented in RichAI.

◆ FinalizeMovement()

virtual void FinalizeMovement ( Vector3  nextPosition,
Quaternion  nextRotation 
)
virtual

Moves the agent to a position.

Parameters
nextPositionNew position of the agent.
nextRotationNew rotation of the agent.

This is used if you want to override how the agent moves. For example if you are using root motion with Mecanim.

This will use a CharacterController, Rigidbody, Rigidbody2D or the Transform component depending on what options are available.

The agent will be clamped to the navmesh after the movement (if such information is available, generally this is only done by the RichAI component).

See also
MovementUpdate for some example code.
controller, rigid, rigid2D

◆ FinalizePosition()

void FinalizePosition ( Vector3  nextPosition)
private

◆ FinalizeRotation()

void FinalizeRotation ( Quaternion  nextRotation)
private

◆ FindComponents()

virtual void FindComponents ( )
protectedvirtual

◆ FixedUpdate()

virtual void FixedUpdate ( )
protectedvirtual

Called every physics update.

If rigidbodies are used then all movement happens here.

◆ GetFeetPosition()

virtual Vector3 GetFeetPosition ( )
virtual

Position of the base of the character.

This is used for pathfinding as the character's pivot point is sometimes placed at the center of the character instead of near the feet. In a building with multiple floors the center of a character may in some scenarios be closer to the navmesh on the floor above than to the floor below which could cause an incorrect path to be calculated. To solve this the start point of the requested paths is always at the base of the character.

◆ Init()

void Init ( )
private

◆ Move()

virtual void Move ( Vector3  deltaPosition)
virtual

Move the agent.

Parameters
deltaPositionDirection and distance to move the agent in world space.

This is intended for external movement forces such as those applied by wind, conveyor belts, knockbacks etc.

Some movement scripts may ignore this completely (notably the AILerp script) if it does not have any concept of being moved externally.

The agent will not be moved immediately when calling this method. Instead this offset will be stored and then applied the next time the agent runs its movement calculations (which is usually later this frame or the next frame). If you want to move the agent immediately then call:

ai.Move(someVector);
ai.FinalizeMovement(ai.position, ai.rotation);

◆ MovementUpdate()

void MovementUpdate ( float  deltaTime,
out Vector3  nextPosition,
out Quaternion  nextRotation 
)

Calculate how the character wants to move during this frame.

Parameters
deltaTimetime to simulate movement for. Usually set to Time.deltaTime.
nextPositionthe position that the agent wants to move to during this frame.
nextRotationthe rotation that the agent wants to rotate to during this frame.

Note that this does not actually move the character. You need to call FinalizeMovement for that. This is called automatically unless canMove is false.

To handle movement yourself you can disable canMove and call this method manually. This code will replicate the normal behavior of the component:

void Update () {
ai.canMove = false;
Vector3 nextPosition;
Quaternion nextRotation;
ai.MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation);
// Modify nextPosition and nextRotation in any way you wish
ai.FinalizeMovement(nextPosition, nextRotation);
}

◆ MovementUpdateInternal()

abstract void MovementUpdateInternal ( float  deltaTime,
out Vector3  nextPosition,
out Quaternion  nextRotation 
)
protectedpure virtual

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

Implemented in RichAI, and AIPath.

◆ OnDisable()

virtual void OnDisable ( )
protectedvirtual

Reimplemented in RichAI, and AIPath.

◆ OnDrawGizmos()

virtual void OnDrawGizmos ( )
protectedvirtual

Reimplemented in RichAI.

◆ OnDrawGizmosSelected()

virtual void OnDrawGizmosSelected ( )
protectedvirtual

◆ OnEnable()

virtual void OnEnable ( )
protectedvirtual

Called when the component is enabled.

◆ OnPathComplete()

abstract void OnPathComplete ( Path  newPath)
pure virtual

Called when a requested path has been calculated.

Implemented in RichAI, AIPath, and LegacyAIPath.

◆ OnUpgradeSerializedData()

override int OnUpgradeSerializedData ( int  version,
bool  unityThread 
)
protectedvirtual

Handle serialization backwards compatibility.

Reimplemented from VersionedMonoBehaviour.

Reimplemented in RichAI, and AIPath.

◆ RaycastPosition()

Vector3 RaycastPosition ( Vector3  position,
float  lastElevation 
)
protected

Checks if the character is grounded and prevents ground penetration.

Parameters
positionPosition of the character in the world.
lastElevationElevation coordinate before the agent was moved. This is along the 'up' axis of the movementPlane.

Sets verticalVelocity to zero if the character is grounded.

Returns
The new position of the character.

◆ RepeatTrySearchPath()

IEnumerator RepeatTrySearchPath ( )
protected

Tries to search for a path every repathRate seconds.

See also
SearchPath

◆ SearchPath()

virtual void SearchPath ( )
virtual

Recalculate the current path.

You can for example use this if you want very quick reaction times when you have changed the destination so that the agent does not have to wait until the next automatic path recalculation (see canSearch).

If there is an ongoing path calculation, it will be canceled, so make sure you leave time for the paths to get calculated before calling this function again. A canceled path will show up in the log with the message "Canceled by script" (see #Seeker.CancelCurrentPathRequest()).

If no destination has been set yet then nothing will be done.

Note
The path result may not become available until after a few frames. During the calculation time the #pathPending property will return true.
See also
#pathPending

Reimplemented in RichAI.

◆ SimulateRotationTowards() [1/2]

Quaternion SimulateRotationTowards ( Vector3  direction,
float  maxDegrees 
)

Simulates rotating the agent towards the specified direction and returns the new rotation.

Parameters
directionDirection in world space to rotate towards.
maxDegreesMaximum number of degrees to rotate this frame.

Note that this only calculates a new rotation, it does not change the actual rotation of the agent. Useful when you are handling movement externally using FinalizeMovement but you want to use the built-in rotation code.

See also
rotationIn2D

◆ SimulateRotationTowards() [2/2]

Quaternion SimulateRotationTowards ( Vector2  direction,
float  maxDegrees 
)
protected

Simulates rotating the agent towards the specified direction and returns the new rotation.

Parameters
directionDirection in the movement plane to rotate towards.
maxDegreesMaximum number of degrees to rotate this frame.

Note that this only calculates a new rotation, it does not change the actual rotation of the agent.

See also
rotationIn2D
movementPlane

◆ Start()

virtual void Start ( )
protectedvirtual

Starts searching for paths.

If you override this method you should in most cases call base.Start () at the start of it.

See also
Init

Reimplemented in LocalSpaceRichAI, and MineBotAI.

◆ Teleport()

virtual 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 in RichAI, and AIPath.

◆ Update()

virtual void Update ( )
protectedvirtual

Called every frame.

If no rigidbodies are used then all movement happens here.

Reimplemented in LegacyAIPath, MineBotAI, LocalSpaceRichAI, and LegacyRichAI.

◆ UpdateVelocity()

void UpdateVelocity ( )
protected

Member Data Documentation

◆ accumulatedMovementDelta

Vector3 accumulatedMovementDelta = Vector3.zero
private

Accumulated movement deltas from the Move method.

◆ canMove

bool canMove = true

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 canSearch = true

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

◆ centerOffset

float centerOffset = 1

Offset along the Y coordinate for the ground raycast start position.

Normally the pivot of the character is at the character's feet, but you usually want to fire the raycast from the character's center, so this value should be half of the character's height.

A green gizmo line will be drawn upwards from the pivot point of the character to indicate where the raycast will start.

See also
gravity

◆ controller

CharacterController controller
protected

Cached CharacterController component.

◆ GizmoColorRaycast

readonly Color GizmoColorRaycast = new Color(118.0f/255, 206.0f/255, 112.0f/255)
staticprotected

◆ gravity

Vector3 gravity = new Vector3(float.NaN, float.NaN, float.NaN)

Gravity to use.

If set to (NaN,NaN,NaN) then Physics.Gravity (configured in the Unity project settings) will be used. If set to (0,0,0) then no gravity will be used and no raycast to check for ground penetration will be performed.

◆ groundMask

LayerMask groundMask = -1

Layer mask to use for ground placement.

Make sure this does not include the layer of any colliders attached to this gameobject.

See also
gravity
https://docs.unity3d.com/Manual/Layers.html

◆ lastDeltaPosition

Vector2 lastDeltaPosition
protected

Amount which the character wants or tried to move with during the last frame.

◆ lastDeltaTime

float lastDeltaTime
protected

Delta time used for movement during the last frame.

◆ lastRepath

float lastRepath = float.NegativeInfinity
protected

Time when the last path request was started.

◆ maxSpeed

float maxSpeed = 1

Max speed in world units per second.

◆ movementPlane

Plane which this agent is moving in.

This is used to convert between world space and a movement plane to make it possible to use this script in both 2D games and 3D games.

◆ prevFrame

int prevFrame
protected

Last frame index when prevPosition1 was updated.

◆ prevPosition1

Vector3 prevPosition1
protected

Position of the character at the end of the last frame.

◆ prevPosition2

Vector3 prevPosition2
protected

Position of the character at the end of the frame before the last frame.

◆ repathRate

float repathRate = 0.5f

Determines how often the agent will search for new paths (in seconds).

The agent will plan a new path to the target every N seconds.

If you have fast moving targets or AIs, you might want to set it to a lower value.

See also
RepeatTrySearchPath

◆ rigid

Rigidbody rigid
protected

Cached Rigidbody component.

◆ rigid2D

Rigidbody2D rigid2D
protected

Cached Rigidbody component.

◆ rotationIn2D

bool rotationIn2D = false

If true, the forward axis of the character will be along the Y axis instead of the Z axis.

For 3D games you most likely want to leave this the default value which is false. For 2D games you most likely want to change this to true as in 2D games you usually want the Y axis to be the forwards direction of the character.

◆ rvoController

RVOController rvoController
protected

Cached RVOController component.

◆ seeker

Seeker seeker
protected

Cached Seeker component.

◆ simulatedPosition

Vector3 simulatedPosition
protected

Position of the agent.

If updatePosition is true then this value will be synchronized every frame with Transform.position.

◆ simulatedRotation

Quaternion simulatedRotation
protected

Rotation of the agent.

If updateRotation is true then this value will be synchronized every frame with Transform.rotation.

◆ startHasRun

bool startHasRun = false
private

True if the Start method has been executed.

Used to test if coroutines should be started in OnEnable to prevent calculating paths in the awake stage (or rather before start on frame 0).

◆ targetCompatibility

Transform targetCompatibility
private

◆ tr

Transform tr
protected

Cached Transform component.

◆ updatePosition

bool updatePosition = true

Determines if the character's position should be coupled to the Transform's position.

If false then all movement calculations will happen as usual, but the object that this component is attached to will not move instead only the position property will change.

This is useful if you want to control the movement of the character using some other means such as for example root motion but still want the AI to move freely.

See also
Combined with calling MovementUpdate from a separate script instead of it being called automatically one can take a similar approach to what is documented here: https://docs.unity3d.com/Manual/nav-CouplingAnimationAndNavigation.html
canMove which in contrast to this field will disable all movement calculations.
updateRotation

◆ updateRotation

bool updateRotation = true

Determines if the character's rotation should be coupled to the Transform's rotation.

If false then all movement calculations will happen as usual, but the object that this component is attached to will not rotate instead only the rotation property will change.

See also
updatePosition

◆ velocity2D

Vector2 velocity2D
protected

Current desired velocity of the agent (does not include local avoidance and physics).

Lies in the movement plane.

◆ verticalVelocity

float verticalVelocity
protected

Velocity due to gravity.

Perpendicular to the movement plane.

When the agent is grounded this may not accurately reflect the velocity of the agent. It may be non-zero even though the agent is not moving.

◆ waitingForPathCalculation

bool waitingForPathCalculation = false
protected

Only when the previous path has been calculated should the script consider searching for a new path.

Property Documentation

◆ desiredVelocity

Vector3 desiredVelocity
get

Velocity that this agent wants to move with.

Includes gravity and local avoidance if applicable.

◆ destination

Vector3 destination
getset

Position in the world that this agent should move to.

If no destination has been set yet, then (+infinity, +infinity, +infinity) will be returned.

Note that setting this property does not immediately cause the agent to recalculate its path. So it may take some time before the agent starts to move towards this point. Most movement scripts have a repathRate field which indicates how often the agent looks for a new path. You can also call the SearchPath method to immediately start to search for a new path. Paths are calculated asynchronously so when an agent starts to search for path it may take a few frames (usually 1 or 2) until the result is available. During this time the #pathPending property will return true.

If you are setting a destination and then want to know when the agent has reached that destination then you should check both #pathPending and #reachedEndOfPath:

IEnumerator Start () {
ai.destination = somePoint;
// Start to search for a path to the destination immediately
// Note that the result may not become available until after a few frames
// ai.pathPending will be true while the path is being calculated
ai.SearchPath();
// Wait until we know for sure that the agent has calculated a path to the destination we set above
while (ai.pathPending || !ai.reachedEndOfPath) {
yield return null;
}
// The agent has reached the destination now
}

◆ isStopped

bool isStopped
getset

Gets or sets if the agent should stop moving.

If this is set to true the agent will immediately start to slow down as quickly as it can to come to a full stop. The agent will still react to local avoidance and gravity (if applicable), but it will not try to move in any particular direction.

The current path of the agent will not be cleared, so when this is set to false again the agent will continue moving along the previous path.

This is a purely user-controlled parameter, so for example it is not set automatically when the agent stops moving because it has reached the target. Use #reachedEndOfPath for that.

If this property is set to true while the agent is traversing an off-mesh link (RichAI script only), then the agent will continue traversing the link and stop once it has completed it.

Note
This is not the same as the canMove setting which some movement scripts have. The canMove setting disables movement calculations completely (which among other things makes it not be affected by local avoidance or gravity). For the AILerp movement script which doesn't use gravity or local avoidance anyway changing this property is very similar to changing canMove.

The #steeringTarget property will continue to indicate the point which the agent would move towards if it would not be stopped.

◆ onSearchPath

System.Action onSearchPath
getset

Called when the agent recalculates its path.

This is called both for automatic path recalculations (see canSearch) and manual ones (see SearchPath).

See also
Take a look at the Pathfinding.AIDestinationSetter source code for an example of how it can be used.

◆ position

Vector3 position
get

Position of the agent.

In world space. If updatePosition is true then this value is idential to transform.position.

See also
Teleport
Move

◆ rotation

Quaternion rotation
get

Rotation of the agent.

If updateRotation is true then this value is identical to transform.rotation.

◆ shouldRecalculatePath

virtual bool shouldRecalculatePath
getprotected

True if the path should be automatically recalculated as soon as possible.

◆ target

Transform target
getset

Target to move towards.

The AI will try to follow/move towards this target. 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.

Deprecated:
In 4.1 this will automatically add a AIDestinationSetter component and set the target on that component. Try instead to use the destination property which does not require a transform to be created as the target or use the AIDestinationSetter component directly.

◆ usingGravity

bool usingGravity
getprivate setprotected

Indicates if gravity is used during this frame.

◆ velocity

Vector3 velocity
get

Actual velocity that the agent is moving with.

In world units per second.

See also
desiredVelocity

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