A* Pathfinding Project  4.0.7
The A* Pathfinding Project for Unity 3D
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Events Macros Groups Pages
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 target.

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).
 
virtual Vector3 GetFeetPosition ()
 
void OnDisable ()
 
virtual void OnPathComplete (Path _p)
 Called when a requested path has finished calculation.
 
virtual void OnTargetReached ()
 
virtual void SearchPath ()
 Requests a path to the target.
 
float TrySearchPath ()
 Tries to search for a path.
 

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.
 
bool canMove = true
 Enables or disables movement.
 
bool canSearch = true
 Enables or disables searching for paths.
 
float endReachedDistance = 0.2F
 Distance to the end point to consider the end of path to be reached.
 
float pickNextWaypointDist = 2
 Determines within what range it will switch to target the next waypoint in the path.
 
float repathRate = 0.5F
 Determines how often it will search for new paths.
 
float rotationSpeed = 360
 Rotation speed.
 
float slowdownDistance = 0.6F
 Distance from the target point where the AI will start to slow down.
 
float speed = 3
 Maximum velocity.
 
Transform target
 Target to move towards.
 
- Public Attributes inherited from AIBase
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.
 

Protected Member Functions

override void MovementUpdate (float deltaTime)
 Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not.
 
virtual void OnEnable ()
 Called when the component is enabled.
 
override int OnUpgradeSerializedData (int version)
 Handle serialization backwards compatibility.
 
IEnumerator RepeatTrySearchPath ()
 Tries to search for a path every repathRate seconds.
 
virtual void Start ()
 Starts searching for paths.
 
- Protected Member Functions inherited from AIBase
void ApplyGravity (float deltaTime)
 
override void Awake ()
 Initializes reference variables.
 
Vector2 CalculateDeltaToMoveThisFrame (Vector2 position, float distanceToEndOfPath, float deltaTime)
 
virtual Vector3 ClampToNavmesh (Vector3 position)
 Constrains the character's position to lie on the navmesh.
 
virtual void FixedUpdate ()
 Called every physics update.
 
void Move (Vector3 position3D, Vector3 deltaPosition)
 
virtual void OnDrawGizmos ()
 
Vector3 RaycastPosition (Vector3 position, float lastElevation)
 Find the world position of the ground below the character.
 
virtual void RotateTowards (Vector2 direction, float maxDegrees)
 Rotates in the specified direction.
 
virtual void Update ()
 Called every frame.
 

Protected Attributes

bool canSearchAgain = true
 Only when the previous path has been returned should be search for a new path.
 
PathInterpolator interpolator = new PathInterpolator()
 
float lastRepath = -9999
 Time when the last path request was sent.
 
Path path
 Current path which is followed.
 
Vector3 targetPoint
 Point to where the AI is heading.
 
Vector3 velocity
 
- Protected Attributes inherited from AIBase
CharacterController controller
 Cached CharacterController component.
 
IMovementPlane movementPlane = GraphTransform.identityTransform
 
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.
 
float verticalVelocity
 Velocity due to gravity.
 

Properties

Vector3 targetDirection [get]
 Direction that the agent wants to move in (excluding physics and local avoidance).
 
bool TargetReached [get, set]
 True if the end of the path has been reached.
 
float turningSpeed [get, set]
 Rotation speed.
 
- Properties inherited from AIBase
bool usingGravity [get, set]
 Indicates if gravity is used during this frame.
 

Private Member Functions

void Init ()
 

Private Attributes

bool startHasRun = false
 True if the Start function has been executed.
 

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

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 velocity property instead.
virtual Vector3 GetFeetPosition ( )
virtual
void Init ( )
private
override void MovementUpdate ( float  deltaTime)
protectedvirtual

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

Implements AIBase.

void OnDisable ( )
virtual void OnEnable ( )
protectedvirtual

Called when the component is enabled.

virtual void OnPathComplete ( Path  _p)
virtual

Called when a requested path has finished calculation.

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

Reimplemented in LegacyAIPath.

virtual void OnTargetReached ( )
virtual

Reimplemented in MineBotAI.

override int OnUpgradeSerializedData ( int  version)
protectedvirtual

Handle serialization backwards compatibility.

Reimplemented from VersionedMonoBehaviour.

IEnumerator RepeatTrySearchPath ( )
protected

Tries to search for a path every repathRate seconds.

See Also
TrySearchPath
virtual void SearchPath ( )
virtual

Requests a path to the target.

virtual void Start ( )
protectedvirtual

Starts searching for paths.

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

See Also
Init

Reimplemented in MineBotAI.

float TrySearchPath ( )

Tries to search for a path.

Will search for a new path if there was a sufficient time since the last repath and both canSearchAgain and canSearch are true and there is a target.

Returns
The time to wait until calling this function again (based on repathRate)

Member Data Documentation

bool alwaysDrawGizmos

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

bool canMove = true

Enables or disables movement.

See Also
canSearch
bool canSearch = true

Enables or disables searching for paths.

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

See Also
canMove
bool canSearchAgain = true
protected

Only when the previous path has been returned should be search for a new path.

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.

PathInterpolator interpolator = new PathInterpolator()
protected
float lastRepath = -9999
protected

Time when the last path request was sent.

Path path
protected

Current path which is followed.

float pickNextWaypointDist = 2

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

float repathRate = 0.5F

Determines how often it will search for new paths.

If you have fast moving targets or AIs, you might want to set it to a lower value. The value is in seconds between path requests.

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.

float slowdownDistance = 0.6F

Distance from the target point where the AI will start to slow down.

Note that this doesn't only affect the end point of the path but also any intermediate points, so be sure to set pickNextWaypointDist to a higher value than this

float speed = 3

Maximum velocity.

This is the maximum speed in world units per second.

bool startHasRun = false
private

True if the Start function 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 target

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.

Vector3 targetPoint
protected

Point to where the AI is heading.

Vector3 velocity
protected

Property Documentation

Vector3 targetDirection
get

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

Deprecated:
Only exists for compatibility reasons.
bool TargetReached
getset

True if the end of the path has been reached.

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