A* Pathfinding Project
4.1.0
The A* Pathfinding Project for Unity 3D
|
AI for following paths. More...
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 destination.
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.
Public Member Functions | |
Vector3 | CalculateVelocity (Vector3 position) |
Current desired velocity of the agent (excluding physics and local avoidance but it includes gravity). | |
override void | OnPathComplete (Path newPath) |
Called when a requested path has been calculated. | |
virtual void | OnTargetReached () |
The end of the path has been reached. | |
override void | Teleport (Vector3 newPosition, bool clearPath=true) |
Instantly move the agent to a new position. | |
Public Member Functions inherited from AIBase | |
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. | |
virtual void | SearchPath () |
Recalculate the current path. | |
Public Member Functions inherited from IAstarAIMovement | |
Vector3 | ClampToNavmesh (Vector3 position, out bool positionChanged) |
Clamps the agent's position to the navmesh. | |
void | Move (Vector3 position, Vector3 deltaPosition) |
Move the agent. | |
void | RotateTowards (Vector3 direction, float maxDegrees) |
Rotates towards the specified direction. | |
void | UpdateVelocity (Vector3 position) |
To be called after all movement is done with the position of the agent. | |
Public Member Functions inherited from IAstarAI | |
void | MovementUpdate (float deltaTime, bool useGravity) |
Calculate all movement for a single movement step and move the agent. | |
void | SearchPath () |
Recalculate the current path. | |
void | Teleport (Vector3 newPosition, bool clearPath=true) |
Instantly move the agent to a new position. | |
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. | |
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 | rotationSpeed = 360 |
Rotation speed. | |
float | slowdownDistance = 0.6F |
Distance from the target point where the AI will start to slow down. | |
bool | slowWhenNotFacingTarget = true |
Slow down when not facing the target direction. | |
CloseToDestinationMode | whenCloseToDestination = CloseToDestinationMode.Stop |
What to do when within endReachedDistance units from the destination. | |
Public Attributes inherited from AIBase | |
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 | |
override void | MovementUpdateInternal (float deltaTime) |
Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not. | |
override void | OnDisable () |
override int | OnUpgradeSerializedData (int version, bool unityThread) |
Handle serialization backwards compatibility. | |
Protected Member Functions inherited from AIBase | |
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 void | FixedUpdate () |
Called every physics update. | |
virtual void | OnDrawGizmos () |
virtual void | OnEnable () |
Called when the component is enabled. | |
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 | |
PathInterpolator | interpolator = new PathInterpolator() |
Helper which calculates points along the current path. | |
Path | path |
Current path which is followed. | |
Protected Attributes inherited from AIBase | |
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. | |
Properties | |
bool IAstarAI. | canMove [get, set] |
Enables or disables movement completely. | |
bool IAstarAI. | canSearch [get, set] |
Enables or disables recalculating the path at regular intervals. | |
bool | hasPath [get] |
True if this agent currently has a path that it follows. | |
float IAstarAI. | maxSpeed [get, set] |
Max speed in world units per second. | |
bool | pathPending [get] |
True if a path is currently being calculated. | |
Vector3 IAstarAI. | position [get] |
Position of the agent. | |
float | remainingDistance [get] |
Remaining distance along the current path to the destination. | |
float | speed [get, set] |
Maximum speed in world units per second. | |
Vector3 | steeringTarget [get] |
Point on the path which the agent is currently moving towards. | |
Vector3 | targetDirection [get] |
Direction that the agent wants to move in (excluding physics and local avoidance). | |
bool | TargetReached [get] |
True if the end of the path has been reached. | |
bool | targetReached [get, set] |
True if the agent has reached the end of the current path. | |
float | turningSpeed [get, set] |
Rotation speed. | |
Properties inherited from AIBase | |
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 | |
Vector3 IAstarAIMovement. | ClampToNavmesh (Vector3 position, out bool positionChanged) |
Clamps the agent's position to the navmesh. | |
void IAstarAIMovement. | Move (Vector3 position, Vector3 deltaPosition) |
Move the agent. | |
void IAstarAIMovement. | RotateTowards (Vector3 direction, float maxDegrees) |
Rotates towards the specified direction. | |
void IAstarAIMovement. | UpdateVelocity (Vector3 position) |
To be called after all movement is done with the position of the agent. | |
Additional Inherited Members | |
Static Protected Attributes inherited from AIBase | |
static readonly Color | GizmoColorRaycast = new Color(118.0f/255, 206.0f/255, 112.0f/255) |
Vector3 CalculateVelocity | ( | Vector3 | position | ) |
Current desired velocity of the agent (excluding physics and local avoidance but it includes gravity).
|
privatevirtual |
Clamps the agent's position to the navmesh.
position | Position of the agent. |
positionChanged | True if the agent's position had to be modified. |
Reimplemented from AIBase.
|
privatevirtual |
Move the agent.
position | Position of the agent. |
deltaPosition | Direction and distance to move the agent in world space. |
Reimplemented from AIBase.
|
protectedvirtual |
Called during either Update or FixedUpdate depending on if rigidbodies are used for movement or not.
Implements AIBase.
|
protectedvirtual |
Reimplemented from AIBase.
|
virtual |
Called when a requested path has been calculated.
A path is first requested by #UpdatePath, 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.
Implements AIBase.
Reimplemented in LegacyAIPath.
|
virtual |
The end of the path has been reached.
If you want custom logic for when the AI has reached it's destination add it here. You can also create a new script which inherits from this one and override the function in that script.
This method will be called again if a new path is calculated as the destination may have changed. So when the agent is close to the destination this method will typically be called every repathRate seconds.
Reimplemented in MineBotAI.
|
protectedvirtual |
Handle serialization backwards compatibility.
Reimplemented from AIBase.
|
private |
Rotates towards the specified direction.
direction | Direction rotate towards. |
maxDegrees | Maximum number of degrees to rotate this frame. |
|
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.
Reimplemented from AIBase.
|
private |
To be called after all movement is done with the position of the agent.
position | Current position of the agent (as a parameter mostly for performance reasons as reading from transform.position can be slow). |
You have to call this if you are handling movement manually to make sure e.g the velocity field is up to date.This is automatically called by the Move method, so if you are using that method this should not be called.
bool alwaysDrawGizmos |
Draws detailed gizmos constantly in the scene view instead of only when the agent is selected and settings are being modified.
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.
|
protected |
Helper which calculates points along the current 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 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
bool slowWhenNotFacingTarget = true |
Slow down when not facing the target direction.
Incurs at a small performance overhead.
CloseToDestinationMode whenCloseToDestination = CloseToDestinationMode.Stop |
What to do when within endReachedDistance units from the destination.
The character can either stop immediately when it comes within that distance, which is useful for e.g archers or other ranged units that want to fire on a target. Or the character can continue to try to reach the exact destination point and come to a full stop there. This is useful if you want the character to reach the exact point that you specified.
Note that targetReached will become true when the character is within endReachedDistance units from the destination regardless of what this field is set to.
|
getsetprivate |
|
getsetprivate |
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.
|
get |
True if this agent currently has a path that it follows.
|
getsetprivate |
Max speed in world units per second.
|
get |
True if a path is currently being calculated.
|
getprivate |
|
get |
Remaining distance along the current path to the destination.
For the RichAI movement script this may not always be precisely known, especially when far away from the destination. In those cases an approximate distance will be returned.If the agent does not currently have a path, then positive infinity will be returned.
|
getset |
Maximum speed in world units per second.
|
get |
Point on the path which the agent is currently moving towards.
This is usually a point a small distance ahead of the agent or the end of the path.If the agent does not have a path at the moment, then the agent's current position will be returned.
|
get |
Direction that the agent wants to move in (excluding physics and local avoidance).
|
get |
True if the end of the path has been reached.
|
getset |
True if the agent has reached the end of the current path.
|
getset |
Rotation speed.