A* Pathfinding Project  4.1.1
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 Vector3 GetFeetPosition ()
 Position of the base of the character.
 
void MovementUpdate (float deltaTime, bool useGravity)
 Calculate all movement for a single movement step and move the character.
 
abstract void OnPathComplete (Path newPath)
 Called when a requested path has been calculated.
 
virtual void SearchPath ()
 Recalculate the current path.
 
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 should move or if just the desired velocities should be calculated.
 
bool updateRotation = true
 Determines if the character should rotate automatically.
 

Protected Member Functions

 AIBase ()
 
void ApplyGravity (float deltaTime)
 Accelerates the agent downwards.
 
override void Awake ()
 Initializes reference variables.
 
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 FixedUpdate ()
 Called every physics update.
 
virtual void Move (Vector3 position3D, Vector3 deltaPosition)
 Moves the agent using an offset.
 
abstract void MovementUpdateInternal (float deltaTime)
 Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not.
 
virtual void OnDisable ()
 
virtual void OnDrawGizmos ()
 
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.
 
virtual void RotateTowards (Vector2 direction, float maxDegrees)
 Rotates towards the specified direction.
 
virtual void Start ()
 Starts searching for paths.
 
virtual void Update ()
 Called every frame.
 
void UpdateVelocity (Vector3 position)
 

Protected Attributes

CharacterController controller
 Cached CharacterController component.
 
Vector3 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.
 
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.
 
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]
 
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 Init ()
 

Private Attributes

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
override void Awake ( )
protectedvirtual

Initializes reference variables.

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

Reimplemented from VersionedMonoBehaviour.

Reimplemented in LegacyAIPath, and LegacyRichAI.

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

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  position3D,
Vector3  deltaPosition 
)
protectedvirtual

Moves the agent using an offset.

Parameters
position3DPosition of the agent in the world. Reading transform.position is slow, so for performance the parameter is passed in here.
deltaPositionHow much to move the agent.

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

If the agent collides with the ground, then the verticalVelocity will be set to zero.

Sets prevPosition1, prevPosition2.

See Also
controller, rigid, rigid2D
ClampToNavmesh
RaycastPosition

Reimplemented in RichAI, and AIPath.

void MovementUpdate ( float  deltaTime,
bool  useGravity 
)

Calculate all movement for a single movement step and move the character.

This is called automatically unless canMove is false.

abstract void MovementUpdateInternal ( float  deltaTime)
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 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 RotateTowards ( Vector2  direction,
float  maxDegrees 
)
protectedvirtual

Rotates towards the specified direction.

Parameters
directionDirection in the movement plane to rotate towards.
maxDegreesMaximum number of degrees to rotate this frame.
See Also
rotationIn2D
movementPlane
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.

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 ( Vector3  position)
protected

Member Data Documentation

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

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.

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 should move or if just the desired velocities should be calculated.

If false then all movement calculations will happen as usual, only the last step of actually moving the character will be left out.

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

See Also
canMove which in contrast to this field will disable all movement calculations.
bool updateRotation = true

Determines if the character should rotate automatically.

If false then all movement calculations will happen as usual, only the step of actually rotating the character will be left out.

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

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