A* Pathfinding Project
4.2.4
The A* Pathfinding Project for Unity 3D
|
Linearly interpolating movement script. More...
Linearly interpolating movement script.
This movement script will follow the path exactly, it uses linear interpolation to move between the waypoints in the path. This is desirable for some types of games. It also works in 2D.
This depends on what type of movement you are aiming for. If you are aiming for movement where the unit follows the path exactly and move only along the graph connections on a grid/point graph. I recommend that you adjust the StartEndModifier on the Seeker component: set the 'Start Point Snapping' field to 'NodeConnection' and the 'End Point Snapping' field to 'SnapToNode'.
If you on the other hand want smoother movement I recommend setting 'Start Point Snapping' and 'End Point Snapping' to 'ClosestOnNode' and to add the Simple Smooth Modifier to the GameObject as well. Alternatively you can use the Funnel Modifier which works better on navmesh/recast graphs or the RaycastModifier.
You should not combine the Simple Smooth Modifier or the Funnel Modifier with the NodeConnection snapping mode. This may lead to very odd behavior.
You may also want to tweak the rotationSpeed.
Public Member Functions | |
void | FinalizeMovement (Vector3 nextPosition, Quaternion nextRotation) |
Move the agent. More... | |
virtual void | ForceSearchPath () |
Requests a path to the target. More... | |
virtual Vector3 | GetFeetPosition () |
void | MovementUpdate (float deltaTime, out Vector3 nextPosition, out Quaternion nextRotation) |
Calculate how the character wants to move during this frame. More... | |
void | OnDisable () |
virtual void | OnTargetReached () |
The end of the path has been reached. More... | |
virtual void | SearchPath () |
Requests a path to the target. More... | |
void | SetPath (Path path) |
Make the AI follow the specified path. More... | |
void | Teleport (Vector3 position, bool clearPath=true) |
Instantly move the agent to a new position. More... | |
Public Attributes | |
bool | canMove = true |
Enables or disables movement completely. More... | |
bool | canSearch = true |
Enables or disables recalculating the path at regular intervals. More... | |
bool | enableRotation = true |
If true, the AI will rotate to face the movement direction. More... | |
bool | interpolatePathSwitches = true |
If true, some interpolation will be done when a new path has been calculated. More... | |
OrientationMode | orientation = OrientationMode.ZAxisForward |
Determines which direction the agent moves in. More... | |
float | repathRate = 0.5F |
Determines how often it will search for new paths. More... | |
float | rotationSpeed = 10 |
How quickly to rotate. More... | |
float | speed = 3 |
Speed in world units. More... | |
float | switchPathInterpolationSpeed = 5 |
How quickly to interpolate to the new path. More... | |
bool | updatePosition = true |
Determines if the character's position should be coupled to the Transform's position. More... | |
bool | updateRotation = true |
Determines if the character's rotation should be coupled to the Transform's rotation. More... | |
Protected Member Functions | |
AILerp () | |
override void | Awake () |
Initializes reference variables. More... | |
virtual Vector3 | CalculateNextPosition (out Vector3 direction, float deltaTime) |
Calculate the AI's next position (one frame in the future). More... | |
virtual void | ConfigureNewPath () |
Finds the closest point on the current path and configures the interpolator. More... | |
virtual void | ConfigurePathSwitchInterpolation () |
virtual void | OnEnable () |
Called when the component is enabled. More... | |
virtual void | OnPathComplete (Path _p) |
Called when a requested path has finished calculation. More... | |
override int | OnUpgradeSerializedData (int version, bool unityThread) |
Handle serialization backwards compatibility. More... | |
virtual void | Start () |
Starts searching for paths. More... | |
virtual void | Update () |
Protected Member Functions inherited from VersionedMonoBehaviour | |
virtual void | Reset () |
Handle serialization backwards compatibility. More... | |
Protected Attributes | |
bool | canSearchAgain = true |
Only when the previous path has been returned should a search for a new path be done. More... | |
PathInterpolator | interpolator = new PathInterpolator() |
float | lastRepath = -9999 |
Time when the last path request was sent. More... | |
ABPath | path |
Current path which is followed. More... | |
float | pathSwitchInterpolationTime = 0 |
Time since the path was replaced by a new path. More... | |
Vector3 | previousMovementDirection |
Vector3 | previousMovementOrigin |
When a new path was returned, the AI was moving along this ray. More... | |
Seeker | seeker |
Cached Seeker component. More... | |
Transform | tr |
Cached Transform component. More... | |
Properties | |
bool IAstarAI. | canMove [get, set] |
Enables or disables movement completely. More... | |
bool IAstarAI. | canSearch [get, set] |
Enables or disables recalculating the path at regular intervals. More... | |
Vector3 IAstarAI. | desiredVelocity [get] |
Vector3 | destination [get, set] |
bool | hasPath [get] |
True if this agent currently has a path that it follows. More... | |
float IAstarAI. | height [get, set] |
Radius of the agent in world units. More... | |
bool | isStopped [get, set] |
Gets or sets if the agent should stop moving. More... | |
float IAstarAI. | maxSpeed [get, set] |
Max speed in world units per second. More... | |
System.Action | onSearchPath [get, set] |
Called when the agent recalculates its path. More... | |
bool | pathPending [get] |
True if a path is currently being calculated. More... | |
Vector3 | position [get] |
Position of the agent. More... | |
float IAstarAI. | radius [get, set] |
Height of the agent in world units. More... | |
bool | reachedDestination [get] |
True if the ai has reached the destination. More... | |
bool | reachedEndOfPath [get, private set] |
True if the end of the current path has been reached. More... | |
float | remainingDistance [get, set] |
Remaining distance along the current path to the end of the path. More... | |
Quaternion | rotation [get] |
Rotation of the agent. More... | |
bool | rotationIn2D [get, set] |
If true, the forward axis of the character will be along the Y axis instead of the Z axis. More... | |
virtual bool | shouldRecalculatePath [get] |
True if the path should be automatically recalculated as soon as possible. More... | |
Vector3 IAstarAI. | steeringTarget [get] |
Point on the path which the agent is currently moving towards. More... | |
Transform | target [get, set] |
Target to move towards. More... | |
Vector3 IAstarAI. | velocity [get] |
Properties inherited from IAstarAI | |
bool | canMove [get, set] |
Enables or disables movement completely. More... | |
bool | canSearch [get, set] |
Enables or disables recalculating the path at regular intervals. More... | |
Vector3 | desiredVelocity [get] |
Velocity that this agent wants to move with. More... | |
Vector3 | destination [get, set] |
Position in the world that this agent should move to. More... | |
bool | hasPath [get] |
True if this agent currently has a path that it follows. More... | |
float | height [get, set] |
Radius of the agent in world units. More... | |
bool | isStopped [get, set] |
Gets or sets if the agent should stop moving. More... | |
float | maxSpeed [get, set] |
Max speed in world units per second. More... | |
System.Action | onSearchPath [get, set] |
Called when the agent recalculates its path. More... | |
bool | pathPending [get] |
True if a path is currently being calculated. More... | |
Vector3 | position [get] |
Position of the agent. More... | |
float | radius [get, set] |
Height of the agent in world units. More... | |
bool | reachedDestination [get] |
True if the ai has reached the destination. More... | |
bool | reachedEndOfPath [get] |
True if the agent has reached the end of the current path. More... | |
float | remainingDistance [get] |
Remaining distance along the current path to the end of the path. More... | |
Quaternion | rotation [get] |
Rotation of the agent. More... | |
Vector3 | steeringTarget [get] |
Point on the path which the agent is currently moving towards. More... | |
Vector3 | velocity [get] |
Actual velocity that the agent is moving with. More... | |
Private Member Functions | |
void | Init () |
void IAstarAI. | Move (Vector3 deltaPosition) |
Move the agent. More... | |
Quaternion | SimulateRotationTowards (Vector3 direction, float deltaTime) |
Private Attributes | |
Vector3 | previousPosition1 |
Vector3 | previousPosition2 |
Vector3 | simulatedPosition |
Quaternion | simulatedRotation |
bool | startHasRun = false |
Holds if the Start function has been run. More... | |
Transform | targetCompatibility |
Required for serialization backward compatibility. More... | |
|
protected |
|
protectedvirtual |
Initializes reference variables.
If you override this function you should in most cases call base.Awake () at the start of it.
Reimplemented from VersionedMonoBehaviour.
|
protectedvirtual |
Calculate the AI's next position (one frame in the future).
direction | The tangent of the segment the AI is currently traversing. Not normalized. |
|
protectedvirtual |
Finds the closest point on the current path and configures the interpolator.
|
protectedvirtual |
void FinalizeMovement | ( | Vector3 | nextPosition, |
Quaternion | nextRotation | ||
) |
Move the agent.
To be called as the last step when you are handling movement manually.
The movement will be clamped to the navmesh if applicable (this is done for the RichAI movement script).
Implements IAstarAI.
|
virtual |
Requests a path to the target.
|
virtual |
|
private |
|
private |
Move the agent.
deltaPosition | Direction 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:
Implements IAstarAI.
void MovementUpdate | ( | float | deltaTime, |
out Vector3 | nextPosition, | ||
out Quaternion | nextRotation | ||
) |
Calculate how the character wants to move during this frame.
deltaTime | time to simulate movement for. Usually set to Time.deltaTime. |
nextPosition | the position that the agent wants to move to during this frame. |
nextRotation | the 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:
Implements IAstarAI.
void OnDisable | ( | ) |
|
protectedvirtual |
Called when the component is enabled.
|
protectedvirtual |
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.
|
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.
|
protectedvirtual |
Handle serialization backwards compatibility.
Reimplemented from VersionedMonoBehaviour.
|
virtual |
Requests a path to the target.
Implements IAstarAI.
void SetPath | ( | Path | path | ) |
Make the AI follow the specified path.
In case the path has not been calculated, the script will call seeker.StartPath to calculate it. This means the AI may not actually start to follow the path until in a few frames when the path has been calculated. The pathPending field will as usual return true while the path is being calculated.
In case the path has already been calculated it will immediately replace the current path the AI is following. This is useful if you want to replace how the AI calculates its paths. Note that if you calculate the path using seeker.StartPath then this script will already pick it up because it is listening for all paths that the Seeker finishes calculating. In that case you do not need to call this function.
You can disable the automatic path recalculation by setting the canSearch field to false.
Implements IAstarAI.
|
private |
|
protectedvirtual |
Starts searching for paths.
If you override this function you should in most cases call base.Start () at the start of it.
void Teleport | ( | Vector3 | newPosition, |
bool | clearPath = true |
||
) |
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.
Implements IAstarAI.
|
protectedvirtual |
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.
This is also useful if you want to have full control over when the movement calculations run. Take a look at MovementUpdate
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.
|
protected |
Only when the previous path has been returned should a search for a new path be done.
bool enableRotation = true |
If true, the AI will rotate to face the movement direction.
bool interpolatePathSwitches = true |
If true, some interpolation will be done when a new path has been calculated.
This is used to avoid short distance teleportation.
|
protected |
|
protected |
Time when the last path request was sent.
OrientationMode orientation = OrientationMode.ZAxisForward |
Determines which direction the agent moves in.
For 3D games you most likely want the ZAxisIsForward option as that is the convention for 3D games. For 2D games you most likely want the YAxisIsForward option as that is the convention for 2D games.
Using the YAxisForward option will also allow the agent to assume that the movement will happen in the 2D (XY) plane instead of the XZ plane if it does not know. This is important only for the point graph which does not have a well defined up direction. The other built-in graphs (e.g the grid graph) will all tell the agent which movement plane it is supposed to use.
|
protected |
Current path which is followed.
|
protected |
Time since the path was replaced by a new path.
|
protected |
|
protected |
When a new path was returned, the AI was moving along this ray.
Used to smoothly interpolate between the previous movement and the movement along the new path. The speed is equal to movement direction.
|
private |
|
private |
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 = 10 |
How quickly to rotate.
|
private |
|
private |
float speed = 3 |
Speed in world units.
|
private |
Holds if the Start function has been run.
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).
float switchPathInterpolationSpeed = 5 |
How quickly to interpolate to the new path.
|
private |
Required for serialization backward compatibility.
|
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.
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.
|
getsetprivate |
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.
This is also useful if you want to have full control over when the movement calculations run. Take a look at MovementUpdate
|
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.
|
getprivate |
|
getset |
|
get |
True if this agent currently has a path that it follows.
|
getsetprivate |
Radius of the agent in world units.
This is visualized in the scene view as a yellow cylinder around the character.
|
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 reachedEndOfPath 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.
The steeringTarget property will continue to indicate the point which the agent would move towards if it would not be stopped.
|
getsetprivate |
Max speed in world units per second.
|
getset |
Called when the agent recalculates its path.
This is called both for automatic path recalculations (see canSearch) and manual ones (see SearchPath).
|
get |
True if a path is currently being calculated.
|
get |
|
getsetprivate |
Height of the agent in world units.
This is visualized in the scene view as a yellow cylinder around the character.
This value is currently only used if an RVOController is attached to the same GameObject, otherwise it is only used for drawing nice gizmos in the scene view. However since the height value is used for some things, the radius field is always visible for consistency and easier visualization of the character. That said, it may be used for something in a future release.
|
get |
True if the ai has reached the destination.
This is a best effort calculation to see if the destination has been reached. For the AIPath/RichAI scripts, this is when the character is within endReachedDistance world units from the destination. For the AILerp script it is when the character is at the destination (±a very small margin).
This value will be updated immediately when the destination is changed (in contrast to reachedEndOfPath), however since path requests are asynchronous it will use an approximation until it sees the real path result. What this property does is to check the distance to the end of the current path, and add to that the distance from the end of the path to the destination (i.e. is assumes it is possible to move in a straight line between the end of the current path to the destination) and then checks if that total distance is less than #endReachedDistance. This property is therefore only a best effort, but it will work well for almost all use cases.
Furthermore it will not report that the destination is reached if the destination is above the head of the character or more than half the height of the character below its feet (so if you have a multilevel building, it is important that you configure the height of the character correctly).
The cases which could be problematic are if an agent is standing next to a very thin wall and the destination suddenly changes to the other side of that thin wall. During the time that it takes for the path to be calculated the agent may see itself as alredy having reached the destination because the destination only moved a very small distance (the wall was thin), even though it may actually be quite a long way around the wall to the other side.
In contrast to reachedEndOfPath, this property is immediately updated when the destination is changed.
|
getprivate set |
True if the end of the current path has been reached.
|
getset |
Remaining distance along the current path to the end of the path.
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.
|
get |
|
getset |
If true, the forward axis of the character will be along the Y axis instead of the Z axis.
|
getprotected |
True if the path should be automatically recalculated as soon as possible.
|
getprivate |
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.
|
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.
|
getprivate |