Class AIPath Extends AIBase, IAstarAI

Public

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 move to a given destination. At regular intervals, the path to the destination will be recalculated. If you want to make the AI to follow a particular object you can attach the AIDestinationSetter component. Take a look at the Get Started Guide tutorial for more instructions on how to configure this script.

Here is a video of this script being used move an agent around (it also uses the MineBotAnimation component to drive the animations):

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 period setting 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 destination field 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 maxSpeed is self-explanatory, as is rotationSpeed. however slowdownDistance might require some explanation: It is the approximate distance from the target where the AI will start to slow down. Setting it to a large value will make the AI slow down very gradually. pickNextWaypointDist determines the distance to the point the AI will move to (see image below).

Below is an image illustrating several variables that are exposed by this class (pickNextWaypointDist, steeringTarget, desiredVelocity)

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 finds a character controller it will also use that. If it finds a rigidbody it will use that. Lastly it will fall back to simply modifying Transform.position which is guaranteed to always work and is also the most performant option.

How it works

In this section I'm going to go over how this script is structured and how information flows. This is useful if you want to make changes to this script or if you just want to understand how it works a bit more deeply. However you do not need to read this section if you are just going to use the script as-is.

This script inherits from the AIBase class. The movement happens either in Unity's standard Update or FixedUpdate method. They are both defined in the AIBase class. Which one is actually used depends on if a rigidbody is used for movement or not. Rigidbody movement has to be done inside the FixedUpdate method while otherwise it is better to do it in Update.

From there a call is made to the MovementUpdate method (which in turn calls MovementUpdateInternal). This method contains the main bulk of the code and calculates how the AI *wants* to move. However it doesn't do any movement itself. Instead it returns the position and rotation it wants the AI to move to have at the end of the frame. The Update (or FixedUpdate) method then passes these values to the FinalizeMovement method which is responsible for actually moving the character. That method also handles things like making sure the AI doesn't fall through the ground using raycasting.

The AI recalculates its path regularly. This happens in the Update method which checks shouldRecalculatePath, and if that returns true it will call SearchPath. The SearchPath method will prepare a path request and send it to the Seeker component, which should be attached to the same GameObject as this script.

Public Methods

GetRemainingPath (buffer, [partsBuffer], stale)

Fills buffer with the remaining path.

Teleport (newPosition, clearPath=true)

Instantly move the agent to a new position.

Public Variables

alwaysDrawGizmos

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

Public
constrainInsideGraph

Ensure that the character is always on the traversable surface of the navmesh.

Public
endOfPath

End point of path the agent is currently following.

Public
hasPath

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

Public
maxAcceleration

How quickly the agent accelerates.

Public
pathPending

True if a path is currently being calculated.

Public
pickNextWaypointDist

How far the AI looks ahead along the path to determine the point it moves to.

Public
preventMovingBackwards

Prevent the velocity from being too far away from the forward direction of the character.

Public
reachedDestination

True if the ai has reached the destination.

Public
reachedEndOfPath

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

Public
remainingDistance

Approximate remaining distance along the current path to the end of the path.

Public
rotationSpeed

Rotation speed in degrees per second.

Public
slowWhenNotFacingTarget

Slow down when not facing the target direction.

Public
slowdownDistance

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

Public
steeringTarget

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

Public

Inherited Public Members

FinalizeMovement (nextPosition, nextRotation)

Moves the agent to a position.

Looks for any attached components like RVOController and CharacterController etc.

Position of the base of the character.

Move (deltaPosition)

Move the agent.

MovementUpdate (deltaTime, nextPosition, nextRotation)

Calculate how the character wants to move during this frame.

Recalculate the current path.

SetPath (path, updateDestinationFromPath=true)

Make the AI follow the specified path.

ShapeGizmoColor
Public Static Readonly
SimulateRotationTowards (direction, ...)

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

autoRepath

Determines how the agent recalculates its path automatically.

Public
canMove

Enables or disables movement completely.

Public
desiredVelocity

Velocity that this agent wants to move with.

Public
desiredVelocityWithoutLocalAvoidance

Velocity that this agent wants to move with before taking local avoidance into account.

Public
destination

Position in the world that this agent should move to.

Public
enableRotation

If true, the AI will rotate to face the movement direction.

Public
endReachedDistance

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

Public
gravity

Gravity to use.

Public
groundMask

Layer mask to use for ground placement.

Public
height

Height of the agent in world units.

Public
isStopped

Gets or sets if the agent should stop moving.

Public
maxSpeed

Max speed in world units per second.

Public
movementPlane

Plane which this agent is moving in.

Public
onSearchPath

Called when the agent recalculates its path.

Public
orientation

Determines which direction the agent moves in.

Public
position

Position of the agent.

Public
radius

Radius of the agent in world units.

Public
rotation

Rotation of the agent.

Public
rvoDensityBehavior

Controls if the agent slows down to a stop if the area around the destination is crowded.

Public
updatePosition

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

Public
updateRotation

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

Public
velocity

Actual velocity that the agent is moving with.

Public
whenCloseToDestination

What to do when within endReachedDistance units from the destination.

Public

Private/Protected Members

ApplyGravity (deltaTime)

Accelerates the agent downwards.

Awake ()
CalculateDeltaToMoveThisFrame (position, distanceToEndOfPath, deltaTime)

Calculates how far to move during a single frame.

CalculateNextRotation (slowdown, avoidingOtherAgents, nextRotation)

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

ClampToNavmesh (position, positionChanged)

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

Clears the current path of the agent.

GizmoColor
Protected Static Readonly
MovementUpdateInternal (deltaTime, nextPosition, nextRotation)

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

Called when the component is enabled.

OnPathComplete (newPath)

Called when a requested path has been calculated.

OnUpdate (dt)

Called every frame.

OnUpgradeSerializedData (migrations, unityThread)

RaycastPosition (position, lastElevation)

Checks if the character is grounded and prevents ground penetration.

Reset ()

Handle serialization backwards compatibility.

Start ()

Starts searching for paths.

UpgradeSerializedData (isUnityThread)
accumulatedMovementDelta

Accumulated movement deltas from the Move method.

Protected
cachedNNConstraint
Private Static
canMove

Enables or disables movement completely.

Private
canSearch

Enables or disables recalculating the path at regular intervals.

Private
controller

Cached CharacterController component.

Protected
gizmoHash
Private
height

Height of the agent in world units.

Private
interpolator

Represents the current steering target for the agent.

Protected
interpolatorPath

Helper which calculates points along the current path.

Protected
lastChangedTime
Private
lastDeltaPosition

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

Protected
lastDeltaTime

Delta time used for movement during the last frame.

Protected
lastRaycastHit

Hit info from the last raycast done for ground placement.

Protected
lastRepath

Time when the last path request was started.

Protected
maxSpeed

Max speed in world units per second.

Private
movementPlane

The plane the agent is moving in.

Private
onPathComplete

Cached delegate for the OnPathComplete method.

Protected
path

Current path which is followed.

Protected
prevPosition1

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

Protected
prevPosition2

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

Protected
radius

Radius of the agent in world units.

Private
rigid

Cached Rigidbody component.

Protected
rigid2D

Cached Rigidbody component.

Protected
rotationFilterState
Private
rotationFilterState2
Private
rvoController

Cached RVOController component.

Protected
seeker

Cached Seeker component.

Protected
shouldRecalculatePath

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

Protected
simulatedPosition

Position of the agent.

Protected
simulatedRotation

Rotation of the agent.

Protected
startHasRun

True if the Start method has been executed.

Protected
tr

Cached Transform component.

Protected
usingGravity

Indicates if gravity is used during this frame.

Protected
velocity2D

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

Protected
verticalVelocity

Velocity due to gravity.

Protected
waitingForPathCalculation

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

Protected

Deprecated Members

The end of the path has been reached.