A* Pathfinding Project  4.1.4
The A* Pathfinding Project for Unity 3D
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Events Macros Groups Pages
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.
 
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.
 
abstract void OnPathComplete (Path newPath)
 Called when a requested path has been calculated.
 
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.
 
virtual void Teleport (Vector3 newPosition, bool clearPath=true)
 Instantly move the agent to a new position.
 

Public Attributes

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

 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.
 
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.
 
virtual void OnDisable ()
 
virtual void OnDrawGizmos ()
 
virtual void OnDrawGizmosSelected ()
 
virtual void OnEnable ()
 Called when the component is enabled.
 
override int OnUpgradeSerializedData (int version, bool unityThread)
 Handle serialization backwards compatibility.
 
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.
 
virtual void Update ()
 Called every frame.
 
void UpdateVelocity ()
 
- Protected Member Functions inherited from VersionedMonoBehaviour
virtual void Awake ()
 

Protected Attributes

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.
 

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.
 
Vector3 destination [get, set]
 Position in the world that this agent should move to.
 
bool isStopped [get, set]
 Gets or sets if the agent should stop moving.
 
System.Action onSearchPath [get, set]
 Called when the agent recalculates its path.
 
Vector3 position [get]
 Position of the agent.
 
Quaternion rotation [get]
 Rotation of the agent.
 
virtual bool shouldRecalculatePath [get]
 True if the path should be automatically recalculated as soon as possible.
 
Transform target [get, set]
 Target to move towards.
 
bool usingGravity [get, set]
 Indicates if gravity is used during this frame.
 
Vector3 velocity [get]
 Actual velocity that the agent is moving with.
 

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.
 
bool startHasRun = false
 True if the Start method has been executed.
 
Transform targetCompatibility
 

Constructor & Destructor Documentation

AIBase ( )
protected

Member Function Documentation

void ApplyGravity ( float  deltaTime)
protected

Accelerates the agent downwards.

See Also
verticalVelocity
gravity
Vector2 CalculateDeltaToMoveThisFrame ( Vector2  position,
float  distanceToEndOfPath,
float  deltaTime 
)
protected

Calculates how far to move during a single frame.

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.

void CancelCurrentPathRequest ( )
protected
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.

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
void FinalizePosition ( Vector3  nextPosition)
private
void FinalizeRotation ( Quaternion  nextRotation)
private
virtual void FindComponents ( )
protectedvirtual
virtual void FixedUpdate ( )
protectedvirtual

Called every physics update.

If rigidbodies are used then all movement happens here.

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.

void Init ( )
private
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);

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);
}

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.

virtual void OnDisable ( )
protectedvirtual

Reimplemented in RichAI, and AIPath.

virtual void OnDrawGizmos ( )
protectedvirtual

Reimplemented in RichAI.

virtual void OnDrawGizmosSelected ( )
protectedvirtual
virtual void OnEnable ( )
protectedvirtual

Called when the component is enabled.

abstract void OnPathComplete ( Path  newPath)
pure virtual

Called when a requested path has been calculated.

Implemented in RichAI, AIPath, and LegacyAIPath.

override int OnUpgradeSerializedData ( int  version,
bool  unityThread 
)
protectedvirtual

Handle serialization backwards compatibility.

Reimplemented from VersionedMonoBehaviour.

Reimplemented in RichAI, and AIPath.

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.
IEnumerator RepeatTrySearchPath ( )
protected

Tries to search for a path every repathRate seconds.

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

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

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.

virtual void Update ( )
protectedvirtual

Called every frame.

If no rigidbodies are used then all movement happens here.

Reimplemented in LegacyAIPath, MineBotAI, LocalSpaceRichAI, and LegacyRichAI.

void UpdateVelocity ( )
protected

Member Data Documentation

Vector3 accumulatedMovementDelta = Vector3.zero
private

Accumulated movement deltas from the Move method.

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.

See Also
canSearch
isStopped

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

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
CharacterController controller
protected

Cached CharacterController component.

readonly Color GizmoColorRaycast = new Color(118.0f/255, 206.0f/255, 112.0f/255)
staticprotected
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.

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
Vector2 lastDeltaPosition
protected

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

float lastDeltaTime
protected

Delta time used for movement during the last frame.

float lastRepath = float.NegativeInfinity
protected

Time when the last path request was started.

float maxSpeed = 1

Max speed in world units per second.

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.

int prevFrame
protected

Last frame index when prevPosition1 was updated.

Vector3 prevPosition1
protected

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

Vector3 prevPosition2
protected

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

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
Rigidbody rigid
protected

Cached Rigidbody component.

Rigidbody2D rigid2D
protected

Cached Rigidbody component.

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
protected

Cached RVOController component.

Seeker seeker
protected

Cached Seeker component.

Vector3 simulatedPosition
protected

Position of the agent.

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

Quaternion simulatedRotation
protected

Rotation of the agent.

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

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

Transform targetCompatibility
private
Transform tr
protected

Cached Transform component.

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 setting canMove to false 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
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
Vector2 velocity2D
protected

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

Lies in the movement plane.

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.

bool waitingForPathCalculation = false
protected

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

Property Documentation

Vector3 desiredVelocity
get

Velocity that this agent wants to move with.

Includes gravity and local avoidance if applicable.

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 targetReached:

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.targetReached) {
yield return null;
}
// The agent has reached the destination now
}

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

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.

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
Quaternion rotation
get

Rotation of the agent.

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

virtual bool shouldRecalculatePath
getprotected

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

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.0 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.
bool usingGravity
getsetprotected

Indicates if gravity is used during this frame.

Vector3 velocity
get

Actual velocity that the agent is moving with.

In world units per second.


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