Of note is that this component shouldn't be used with a Seeker component. It has its own settings for pathfinding instead, which are stored in the pathfindingSettings field.
Features
Uses Unity's ECS (Entity Component System) to move the agent. This means it is highly-performant and is able to utilize multiple threads.
Supports movement on spherical on non-planar worlds (see Spherical Worlds).
Supports movement on grid graphs as well as navmesh/recast graphs.
Does not support movement on point graphs at the moment. This may be added in a future update.
Supports time-scales greater than 1. The agent will automatically run multiple simulation steps per frame if the time-scale is greater than 1, to ensure stability.
Supports off-mesh links. Subscribe to the onTraverseOffMeshLink event to handle this.
Knows which node it is traversing at all times (see currentNode).
Automatically stops when trying to reach a crowded destination when using local avoidance.
Clamps the agent to the navmesh at all times.
Follows paths very smoothly.
Can keep a desired distance to walls.
Can approach its destination with a desired facing direction.
Inspector
Shape
Radius
Radius of the agent in world units.
This is visualized in the scene view as a yellow cylinder around the character.
Note that this does not affect pathfinding in any way. The graph used completely determines where the agent can move.
Note
The Pathfinding.AILerp script doesn't really have any use of knowing the radius or the height of the character, so this property will always return 0 in that script.
This is visualized in the scene view as a yellow cylinder around the character.
This value is used for various heuristics, and for visualization purposes. For example, the destination is only considered reached if the destination is not above the agent's head, and it's not more than half the agent's height below its feet.
If local lavoidance is enabled, this is also used to filter out collisions with agents and obstacles that are too far above or below the agent.
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.
When using ZAxisForard, the +Z axis will be the forward direction of the agent, +Y will be upwards, and +X will be the right direction.
When using YAxisForward, the +Y axis will be the forward direction of the agent, +Z will be upwards, and +X will be the right direction.
See
This setting corresponds to the member orientation
Movement
Speed
Max speed in world units per second.
See
This setting corresponds to the member maxSpeed
Rotation Speed
Desired rotation speed in degrees per second.
If the agent is in an open area and gets a new destination directly behind itself, it will start to rotate around with exactly this rotation speed.
The agent will slow down its rotation speed as it approaches its desired facing direction. So for example, when it is only 90 degrees away from its desired facing direction, it will only rotate with about half this speed.
See
This setting corresponds to the member rotationSpeed
Max Rotation Speed
Maximum rotation speed in degrees per second.
If the agent would have to rotate faster than this, it will instead slow down to get more time to rotate.
The agent may want to rotate faster than rotationSpeed if there's not enough space, so that it has to move in a more narrow arc. It may also want to rotate faster if it is very close to its destination and it wants to make sure it ends up on the right spot without any circling.
It is recommended to keep this at a value slightly larger than rotationSpeed.
When the agent wants to turn significantly, enabling this will make it turn on the spot instead of moving in an arc. This can make for more responsive and natural movement for humanoid characters.
How much to smooth the visual rotation of the agent.
This does not affect movement, but smoothes out how the agent rotates visually.
Recommended values are between 0.0 and 0.5. A value of zero will disable smoothing completely.
The smoothing is done primarily using an exponential moving average, but with a small linear term to make the rotation converge faster when the agent is almost facing the desired direction.
Adding smoothing will make the visual rotation of the agent lag a bit behind the actual rotation. Too much smoothing may make the agent seem sluggish, and appear to move sideways.
How far away from the destination should the agent aim to stop, in world units.
If the agent is within this distance from the destination point it will be considered to have reached the destination.
Even if you want the agent to stop precisely at a given point, it is recommended to keep this slightly above zero. If it is exactly zero, the agent may have a hard time deciding that it has actually reached the end of the path, due to floating point errors and such.
How wide of a turn to make when approaching a destination for which a desired facing direction has been set.
The following video shows three agents, one with no facing direction set, and then two agents with varying values of the lead in radius.
Setting this to zero will make the agent move directly to the end of the path and rotate on the spot to face the desired facing direction, once it is there.
When approaching a destination for which no desired facing direction has been set, this field has no effect.
Warning
Setting this to a too small (but non-zero) value may look bad if the agent cannot rotate fast enough to stay on the arc.
This will be multiplied by the agent's scale to get the actual radius.
See
This setting corresponds to the member enableGravity
Raycast Ground Mask
Determines which layers the agent will stand on.
The agent will use a raycast each frame to check if it should stop falling.
This layer mask should ideally not contain the agent's own layer, if the agent has a collider, as this may cause it to try to stand on top of itself.
See
This setting corresponds to the member groundMask
Movement Plane Source
How to calculate which direction is "up" for the agent.
In almost all cases, you should use the Graph option. This will make the agent use the graph's natural "up" direction. However, if you are using a spherical world, or a world with some other strange shape, then you may want to use the NavmeshNormal or Raycast options.
This field determines which graphs will be considered when searching for the start and end nodes of a path. It is useful in numerous situations, for example if you want to make one graph for small units and one graph for large units, or one graph for people and one graph for ships.
This is a bitmask so if you for example want to make the agent only use graph index 3 then you can set this to: settings.graphMask = 1 << 3;
Note that this field only stores which graph indices that are allowed. This means that if the graphs change their ordering then this mask may no longer be correct.
If you know the name of the graph you can use the Pathfinding.GraphMask.FromGraphName method: GraphMask mask1 = GraphMask.FromGraphName("My Grid Graph"); GraphMask mask2 = GraphMask.FromGraphName("My Other Grid Graph");
NNConstraint nn = NNConstraint.Walkable;
nn.graphMask = mask1 | mask2;
// Find the node closest to somePoint which is either in 'My Grid Graph' OR in 'My Other Grid Graph' var info = AstarPath.active.GetNearest(somePoint, nn);
This is a bitmask. Each bit indicates that the agent can traverse nodes with the corresponding tag. If a bit is not set, the agent will treat it as if it is not traversable.
The default value is -1, which sets all bits, and indicates that the agent can traverse all tags.
Layer mask specifying which layers this agent will avoid.
You can set it as CollidesWith = RVOLayer.DefaultAgent | RVOLayer.Layer3 | RVOLayer.Layer6 ...
This can be very useful in games which have multiple teams of some sort. For example you usually want the agents in one team to avoid each other, but you do not want them to avoid the enemies.
This field only affects which other agents that this agent will avoid, it does not affect how other agents react to this agent.
Usually a value between 0 and 1. Agents with similar priorities will avoid each other with an equal strength. If an agent sees another agent with a higher priority than itself it will avoid that agent more strongly. In the extreme case (e.g this agent has a priority of 0 and the other agent has a priority of 1) it will treat the other agent as being a moving obstacle. Similarly if an agent sees another agent with a lower priority than itself it will avoid that agent less.
In general the avoidance strength for this agent is: if this.priority > 0 or other.priority > 0: avoidanceStrength = other.priority / (this.priority + other.priority); else: avoidanceStrength = 0.5
The agent considers the destination reached when it is within stopDistance world units from the destination. Additionally, the destination must not be above the agent's head, and it must not be more than half the agent's height below its feet.
If a facing direction was specified when setting the destination, this will only return true once the agent is approximately facing the correct orientation.
This value will be updated immediately when the destination is changed.
IEnumerator Start () { ai.destination = somePoint; // Start to search for a path to the destination immediately ai.SearchPath(); // Wait until the agent has reached the destination while (!ai.reachedDestination) { yield return null; } // The agent has reached the destination now }
Note
The agent may not be able to reach the destination. In that case this property may never become true. Sometimes reachedEndOfPath is more appropriate.
True if the agent has reached the end of the current path.
The agent considers the end of the path reached when it is within stopDistance world units from the end of the path. Additionally, the end of the path must not be above the agent's head, and it must not be more than half the agent's height below its feet.
If a facing direction was specified when setting the destination, this will only return true once the agent is approximately facing the correct orientation.
This value will be updated immediately when the destination is changed.
Note
Reaching the end of the path does not imply that it has reached its desired destination, as the destination may not even be possible to reach. Sometimes reachedDestination is more appropriate.
True if this agent currently has a valid path that it follows.
This is true if the agent has a path and the path is not stale.
A path may become stale if the graph is updated close to the agent and it hasn't had time to recalculate its path yet.
See
This setting corresponds to the member hasPath
Path Pending
True if a path is currently being calculated.
See
This setting corresponds to the member pathPending
Destination
Position in the world that this agent should move to.
If no destination has been set yet, then (+infinity, +infinity, +infinity) will be returned.
Setting this property will immediately try to repair the path if the agent already has a path. This will also immediately update properties like reachedDestination, reachedEndOfPath and remainingDistance.
The agent may do a full path recalculation if the local repair was not sufficient, but this will at earliest happen in the next simulation step.
IEnumerator Start () { ai.destination = somePoint; // Wait until the AI has reached the destination while (!ai.reachedEndOfPath) { yield return null; } // The agent has reached the destination now }
See
SetDestination, which also allows you to set a facing direction for the agent.
See
This setting corresponds to the member destination
Remaining Distance
Approximate remaining distance along the current path to the end of the path.
The agent does not know the true distance at all times, so this is an approximation. It tends to be a bit lower than the true distance.
Note
This is the distance to the end of the path, which may or may not be the same as the destination. If the character cannot reach the destination it will try to move as close as possible to it.
This value will update immediately if the destination property is changed, or if the agent is moved using the position property or the Teleport method.
If the agent has no path, or if the current path is stale (e.g. if the graph has been updated close to the agent, and it hasn't had time to recalculate its path), this will return positive infinity.
See
This setting corresponds to the member velocity
%ECS
This script uses Unity's ECS (Entity Component System) to move the agent. This means it is highly-performant and is able to utilize multiple threads. Internally, an entity is created for the agent with the following components:
Then this script barely does anything by itself. It is a thin wrapper around the ECS components. Instead, actual movement calculations are carried out by the following systems:
In fact, as long as you create the appropriate ECS components, you do not even need this script. You can use the systems directly.
This is not a baked component. That is, this script will continue to work even in standalone games. It is designed to be easily used without having to care too much about the underlying ECS implementation.
This movement script has been written to remedy several inconsistency issues with other movement scrips, to provide very smooth movement, and "just work" for most games.
For example, it goes to great lengths to ensure that the reachedDestination and reachedEndOfPath properties are as accurate as possible at all times, even before it has had time to recalculate its path to account for a new destination. It does this by locally repairing the path (if possible) immediately when the destination changes instead of waiting for a path recalculation. This also has a bonus effect that the agent can often work just fine with moving targets, even if it almost never recalculates its path (though the repaired path may not always be optimal), and it leads to very responsive movement.
In contrast to other movement scripts, this movement script does not use path modifiers at all. Instead, this script contains its own internal FunnelModifier which it uses to simplify the path before it follows it. In also doesn't use a separate RVOController component for local avoidance, but instead it stores local avoidance settings in rvoSettings.
Best practices for good performance
Using ECS components has some downsides. Accessing properties on this script is significantly slower compared to accessing properties on other movement scripts. This is because on each property access, the script has to make sure no jobs are running concurrently, which is a relatively expensive operation. Slow is a relative term, though. This only starts to matter if you have lots of agents, maybe a hundred or so. So don't be scared of using it.
But if you have a lot of agents, it is recommended to not access properties on this script more often than required. Avoid setting fields to the same value over and over again every frame, for example. If you have a moving target, try to use the AIDestinationSetter component instead of setting the destination property manually, as that is faster than setting the destination property every frame.
You can instead write custom ECS systems to access the properties on the ECS components directly. This is much faster. For example, if you want to make the agent follow a particular entity, you could create a new DestinationEntity component which just holds an entity reference, and then create a system that every frame copies that entity's position to the DestinationPoint.destination field (a component that this entity will always have).
This script has some optional parts. Local avoidance, for example. Local avoidance is used to make sure that agents do not overlap each other. However, if you do not need it, you can disable it to improve performance.
The buffer will be cleared and replaced with the path. The first point is the current position of the agent.
out bool
stale
May be true if the path is invalid in some way. For example if the agent has no path or if the agent has detected that some nodes in the path have been destroyed.
)
Fills buffer with the remaining path.
If the agent traverses off-mesh links, the buffer will still contain the whole path. Off-mesh links will be represented by a single line segment. You can use the GetRemainingPath(List<Vector3>,List<PathPartWithLinkInfo>,bool) overload to get more detailed information about the different parts of the path.
var buffer = new List<Vector3>();
ai.GetRemainingPath(buffer, out bool stale); for (int i = 0; i < buffer.Count - 1; i++) { Debug.DrawLine(buffer[i], buffer[i+1], Color.red); }
If not null, this list will be filled with information about the different parts of the path. A part is a sequence of nodes or an off-mesh link.
out bool
stale
May be true if the path is invalid in some way. For example if the agent has no path or if the agent has detected that some nodes in the path have been destroyed.
)
Fills buffer with the remaining path.
var buffer = new List<Vector3>(); var parts = new List<PathPartWithLinkInfo>();
ai.GetRemainingPath(buffer, parts, out bool stale); foreach (var part in parts) { for (int i = part.startIndex; i < part.endIndex; i++) { Debug.DrawLine(buffer[i], buffer[i+1], part.type == Funnel.PartType.NodeSequence ? Color.red : Color.green); } }
Note
The FollowerEntity simplifies its path continuously as it moves along it. This means that the agent may not follow this exact path, if it manages to simplify the path later. Furthermore, the agent will apply a steering behavior on top of this path, to make its movement smoother.
Direction and distance to move the agent in world space.
)
Move the agent.
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.
For the AIPath and RichAI movement scripts, 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: ai.Move(someVector); ai.FinalizeMovement(ai.position, ai.rotation);
The FollowerEntity movement script will, on the other hand, move the agent immediately.
SearchPath
()
Recalculate the current path.
Public
void
SearchPath ()
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.
Set the position in the world that this agent should move to.
Public
void
SetDestination (
float3
destination
float3
facingDirection=default
)
Set the position in the world that this agent should move to.
This method will immediately try to repair the path if the agent already has a path. This will also immediately update properties like reachedDestination, reachedEndOfPath and remainingDistance. The agent may do a full path recalculation if the local repair was not sufficient, but this will at earliest happen in the next simulation step.
If you are setting a destination and want to know when the agent has reached that destination, then you could use either reachedDestination or reachedEndOfPath.
You may also set a facing direction for the agent. If set, the agent will try to approach the destination point with the given heading. reachedDestination and reachedEndOfPath will only return true once the agent is approximately facing the correct direction. The MovementSettings.follower.leadInRadiusWhenApproachingDestination field controls how wide an arc the agent will try to use when approaching the destination.
The following video shows three agents, one with no facing direction set, and then two agents with varying values of the lead in radius.
IEnumerator Start () { ai.SetDestination(somePoint, Vector3.right); // Wait until the AI has reached the destination and is rotated to the right in world space while (!ai.reachedEndOfPath) { yield return null; } // The agent has reached the destination now }
If true, the destination property will be set to the end point of the path. If false, the previous destination value will be kept. If you pass a path which has no well defined destination before it is calculated (e.g. a MultiTargetPath or RandomPath), then the destination will be first be cleared, but once the path has been calculated, it will be set to the end point of the path.
)
Make the AI follow the specified path.
In case the path has not been calculated, the script will schedule the path to be calculated. 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.
If you pass null path, then the current path will be cleared and the agent will stop moving. Note than unless you have also disabled canSearch, then the agent will soon recalculate its path and start moving again.
Note
Stopping the agent by passing a null path works. But this will stop the agent instantly, and it will not be able to use local avoidance or know its place on the navmesh. Usually it's better to set isStopped to false, which will make the agent slow down smoothly.
You can disable the automatic path recalculation by setting the canSearch field to false.
Note
This call will be ignored if the agent is currently traversing an off-mesh link. Furthermore, when an agent starts traversing an off-mesh link, the current path request will be canceled (if one is currently in progress).
IEnumerator Start () { var pointToAvoid = enemy.position; // Make the AI flee from an enemy. // The path will be about 20 world units long (the default cost of moving 1 world unit is 1000). var path = FleePath.Construct(ai.position, pointToAvoid, 1000 * 20); ai.SetPath(path);
while (!ai.reachedEndOfPath) { yield return null; } }
This method is preferred for long distance teleports. If you only move the agent a very small distance (so that it is reasonable that it can keep its current path), then setting the position property is preferred. Setting the position property very far away from the agent could cause the agent to fail to move the full distance, as it can get blocked by the navmesh.
If true, the destination property will be set to the end point of the path. If false, the previous destination value will be kept. If you pass a path which has no well defined destination before it is calculated (e.g. a MultiTargetPath or RandomPath), then the destination will be first be cleared, but once the path has been calculated, it will be set to the end point of the path.
)
Make the AI follow the specified path.
In case the path has not been calculated, the script will schedule the path to be calculated. 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.
If you pass null path, then the current path will be cleared and the agent will stop moving. Note than unless you have also disabled canSearch, then the agent will soon recalculate its path and start moving again.
Note
Stopping the agent by passing a null path works. But this will stop the agent instantly, and it will not be able to use local avoidance or know its place on the navmesh. Usually it's better to set isStopped to false, which will make the agent slow down smoothly.
You can disable the automatic path recalculation by setting the canSearch field to false.
Note
This call will be ignored if the agent is currently traversing an off-mesh link. Furthermore, when an agent starts traversing an off-mesh link, the current path request will be canceled (if one is currently in progress).
IEnumerator Start () { var pointToAvoid = enemy.position; // Make the AI flee from an enemy. // The path will be about 20 world units long (the default cost of moving 1 world unit is 1000). var path = FleePath.Construct(ai.position, pointToAvoid, 1000 * 20); ai.SetPath(path);
while (!ai.reachedEndOfPath) { yield return null; } }
Velocity that this agent wants to move with before taking local avoidance into account.
Includes gravity. In world units per second.
Setting this property will set the current velocity that the agent is trying to move with, including gravity. This can be useful if you want to make the agent come to a complete stop in a single frame or if you want to modify the velocity in some way.
// Set the velocity to zero, but keep the current gravity var newVelocity = new Vector3(0, ai.desiredVelocityWithoutLocalAvoidance.y, 0);
The Pathfinding.AILerp movement script doesn't use local avoidance so this property will always be identical to velocity on that component.
Warning
Trying to set this property on an AILerp component will throw an exception since its velocity cannot meaningfully be changed abitrarily.
If you are not using local avoidance then this property will in almost all cases be identical to desiredVelocity plus some noise due to floating point math.
Position in the world that this agent should move to.
Public
Vector3?
destination
Position in the world that this agent should move to.
If no destination has been set yet, then (+infinity, +infinity, +infinity) will be returned.
Setting this property will immediately try to repair the path if the agent already has a path. This will also immediately update properties like reachedDestination, reachedEndOfPath and remainingDistance.
The agent may do a full path recalculation if the local repair was not sufficient, but this will at earliest happen in the next simulation step.
IEnumerator Start () { ai.destination = somePoint; // Wait until the AI has reached the destination while (!ai.reachedEndOfPath) { yield return null; } // The agent has reached the destination now }
See
SetDestination, which also allows you to set a facing direction for the agent.
enableGravity
Enables or disables gravity.
Public
bool
enableGravity
Enables or disables gravity.
If gravity is enabled, the agent will accelerate downwards, and use a raycast to check if it should stop falling.
End point of path the agent is currently following.
If the agent has no path (or if it's not calculated yet), this will return the destination instead. If the agent has no destination it will return the agent's current position.
The end of the path is usually identical or very close to the destination, but it may differ if the path for example was blocked by a wall, so that the agent couldn't get any closer.
The agent will use a raycast each frame to check if it should stop falling.
This layer mask should ideally not contain the agent's own layer, if the agent has a collider, as this may cause it to try to stand on top of itself.
hasPath
True if this agent currently has a valid path that it follows.
Public
bool
hasPath
True if this agent currently has a valid path that it follows.
This is true if the agent has a path and the path is not stale.
A path may become stale if the graph is updated close to the agent and it hasn't had time to recalculate its path yet.
height
Height of the agent in world units.
Public
float
height
Height of the agent in world units.
This is visualized in the scene view as a yellow cylinder around the character.
This value is used for various heuristics, and for visualization purposes. For example, the destination is only considered reached if the destination is not above the agent's head, and it's not more than half the agent's height below its feet.
If local lavoidance is enabled, this is also used to filter out collisions with agents and obstacles that are too far above or below the agent.
isStopped
Gets or sets if the agent should stop moving.
Public
bool
isStopped
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.
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). For the AILerp movement script which doesn't use gravity or local avoidance anyway changing this property is very similar to changing canMove.
The steeringTarget property will continue to indicate the point which the agent would move towards if it would not be stopped.
isTraversingOffMeshLink
True if the agent is currently traversing an off-mesh link.
Public
bool
isTraversingOffMeshLink
True if the agent is currently traversing an off-mesh link.
If the agent would have to rotate faster than this, it will instead slow down to get more time to rotate.
The agent may want to rotate faster than rotationSpeed if there's not enough space, so that it has to move in a more narrow arc. It may also want to rotate faster if it is very close to its destination and it wants to make sure it ends up on the right spot without any circling.
It is recommended to keep this at a value slightly larger than rotationSpeed.
Provides callbacks during various parts of the movement calculations.
With this property you can register callbacks that will be called during various parts of the movement calculations. These can be used to modify movement of the agent.
The following example demonstrates how one can hook into one of the available phases and modify the agent's movement. In this case, the movement is modified to become wavy.
public class MovementModifierNoise : MonoBehaviour { public float strength = 1; public float frequency = 1; float phase;
public void Start () { // Register a callback to modify the movement. // This will be called during every simulation step for the agent. // This may be called multiple times per frame if the time scale is high or fps is low, // or less than once per frame, if the fps is very high. GetComponent<FollowerEntity>().movementOverrides.AddBeforeControlCallback(MovementOverride);
// Randomize a phase, to make different agents behave differently phase = UnityEngine.Random.value * 1000; }
public void OnDisable () { // Remove the callback when the component is disabled GetComponent<FollowerEntity>().movementOverrides.RemoveBeforeControlCallback(MovementOverride); }
public void MovementOverride (Entity entity, float dt, ref LocalTransform localTransform, ref AgentCylinderShape shape, ref AgentMovementPlane movementPlane, ref DestinationPoint destination, ref MovementState movementState, ref MovementSettings movementSettings) { // Rotate the next corner the agent is moving towards around the agent by a random angle. // This will make the agent appear to move in a drunken fashion.
// Don't modify the movement as much if we are very close to the end of the path var strengthMultiplier = Mathf.Min(1, movementState.remainingDistanceToEndOfPart / Mathf.Max(shape.radius, movementSettings.follower.slowdownTime * movementSettings.follower.speed)); strengthMultiplier *= strengthMultiplier;
// Generate a smoothly varying rotation angle var rotationAngleRad = strength * strengthMultiplier * (Mathf.PerlinNoise1D(Time.time * frequency + phase) - 0.5f); // Clamp it to at most plus or minus 90 degrees rotationAngleRad = Mathf.Clamp(rotationAngleRad, -math.PI*0.5f, math.PI*0.5f);
// Convert the rotation angle to a world-space quaternion. // We use the movement plane to rotate around the agent's up axis, // making this code work in both 2D and 3D games. var rotation = movementPlane.value.ToWorldRotation(rotationAngleRad);
// Rotate the direction to the next corner around the agent movementState.nextCorner = localTransform.Position + math.mul(rotation, movementState.nextCorner - localTransform.Position); } } There are a few different phases that you can register callbacks for:
BeforeControl: Called before the agent's movement is calculated. At this point, the agent has a valid path, and the next corner that is moving towards has been calculated.
AfterControl: Called after the agent's desired movement is calculated. The agent has stored its desired movement in the MovementControl component. Local avoidance has not yet run.
BeforeMovement: Called right before the agent's movement is applied. At this point the agent's final movement (including local avoidance) is stored in the ResolvedMovement component, which you may modify.
Warning
If any agent has a callback registered here, a sync point will be created for all agents when the callback runs. This can make the simulation not able to utilize multiple threads as effectively. If you have a lot of agents, consider using a custom entity component system instead. But as always, profile first to see if this is actually a problem for your game.
The callbacks may be called multiple times per frame, if the fps is low, or if the time scale is high. It may also be called less than once per frame if the fps is very high. Each callback is provided with a dt parameter, which is the time in seconds since the last simulation step. You should prefer using this instead of Time.deltaTime.
This is typically the ground plane, which will be the XZ plane in a 3D game, and the XY plane in a 2D game. Ultimately it depends on the graph orientation.
If you are doing pathfinding on a spherical world (see Spherical Worlds), the the movement plane will be the tangent plane of the sphere at the agent's position.
movementPlaneSource
How to calculate which direction is "up" for the agent.
How to calculate which direction is "up" for the agent.
In almost all cases, you should use the Graph option. This will make the agent use the graph's natural "up" direction. However, if you are using a spherical world, or a world with some other strange shape, then you may want to use the NavmeshNormal or Raycast options.
If the off-mesh link is destroyed while the agent is traversing it, this property will still return the link. But be careful about accessing properties like OffMeshLinkSource.gameObject, as that may refer to a destroyed gameObject.
Callback to be called when an agent starts traversing an off-mesh link.
The handler will be called when the agent starts traversing an off-mesh link. It allows you to to control the agent for the full duration of the link traversal.
Use the passed context struct to get information about the link and to control the agent.
namespace Pathfinding.Examples { public class FollowerJumpLink : MonoBehaviour, IOffMeshLinkHandler, IOffMeshLinkStateMachine { // Register this class as the handler for off-mesh links when the component is enabled void OnEnable() => GetComponent<NodeLink2>().onTraverseOffMeshLink = this; void OnDisable() => GetComponent<NodeLink2>().onTraverseOffMeshLink = null;
IEnumerable IOffMeshLinkStateMachine.OnTraverseOffMeshLink (AgentOffMeshLinkTraversalContext ctx) { var start = (Vector3)ctx.link.relativeStart; var end = (Vector3)ctx.link.relativeEnd; var dir = end - start;
// Disable local avoidance while traversing the off-mesh link. // If it was enabled, it will be automatically re-enabled when the agent finishes traversing the link. ctx.DisableLocalAvoidance();
// Move and rotate the agent to face the other side of the link. // When reaching the off-mesh link, the agent may be facing the wrong direction. while (!ctx.MoveTowards( position: start, rotation: Quaternion.LookRotation(dir, ctx.movementPlane.up), gravity: true, slowdown: true).reached) { yield return null; }
var bezierP0 = start; var bezierP1 = start + Vector3.up*5; var bezierP2 = end + Vector3.up*5; var bezierP3 = end; var jumpDuration = 1.0f;
// Animate the AI to jump from the start to the end of the link for (float t = 0; t < jumpDuration; t += ctx.deltaTime) { ctx.transform.Position = AstarSplines.CubicBezier(bezierP0, bezierP1, bezierP2, bezierP3, Mathf.SmoothStep(0, 1, t / jumpDuration)); yield return null; } } } }
Warning
Off-mesh links can be destroyed or disabled at any moment. The built-in code will attempt to make the agent continue following the link even if it is destroyed, but if you write your own traversal code, you should be aware of this.
You can alternatively set the corresponding property property on the off-mesh link ( NodeLink2.onTraverseOffMeshLink) to specify a callback for a specific off-mesh link.
Note
The agent's off-mesh link handler takes precedence over the link's off-mesh link handler, if both are set.
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.
When using ZAxisForard, the +Z axis will be the forward direction of the agent, +Y will be upwards, and +X will be the right direction.
When using YAxisForward, the +Y axis will be the forward direction of the agent, +Z will be upwards, and +X will be the right direction.
If you want to move the agent you may use Teleport or Move.
positionSmoothing
How much to smooth the visual position of the agent.
Public
float
positionSmoothing
How much to smooth the visual position of the agent.
This does not affect movement, but smoothes out the position of the agent visually.
Recommended values are between 0.0 and 0.5. A value of zero will disable smoothing completely.
This will make the agent seem to lag slightly behind the internal position of the agent. It may also cut corners slightly.
The unit for this field is seconds.
radius
Radius of the agent in world units.
Public
float
radius
Radius of the agent in world units.
This is visualized in the scene view as a yellow cylinder around the character.
Note that this does not affect pathfinding in any way. The graph used completely determines where the agent can move.
Note
The Pathfinding.AILerp script doesn't really have any use of knowing the radius or the height of the character, so this property will always return 0 in that script.
The agent considers the destination reached when it is within stopDistance world units from the destination. Additionally, the destination must not be above the agent's head, and it must not be more than half the agent's height below its feet.
If a facing direction was specified when setting the destination, this will only return true once the agent is approximately facing the correct orientation.
This value will be updated immediately when the destination is changed.
IEnumerator Start () { ai.destination = somePoint; // Start to search for a path to the destination immediately ai.SearchPath(); // Wait until the agent has reached the destination while (!ai.reachedDestination) { yield return null; } // The agent has reached the destination now }
Note
The agent may not be able to reach the destination. In that case this property may never become true. Sometimes reachedEndOfPath is more appropriate.
True if the agent has reached the end of the current path.
Public
bool
reachedEndOfPath
True if the agent has reached the end of the current path.
The agent considers the end of the path reached when it is within stopDistance world units from the end of the path. Additionally, the end of the path must not be above the agent's head, and it must not be more than half the agent's height below its feet.
If a facing direction was specified when setting the destination, this will only return true once the agent is approximately facing the correct orientation.
This value will be updated immediately when the destination is changed.
Note
Reaching the end of the path does not imply that it has reached its desired destination, as the destination may not even be possible to reach. Sometimes reachedDestination is more appropriate.
Approximate remaining distance along the current path to the end of the path.
Public
float
remainingDistance
Approximate remaining distance along the current path to the end of the path.
The agent does not know the true distance at all times, so this is an approximation. It tends to be a bit lower than the true distance.
Note
This is the distance to the end of the path, which may or may not be the same as the destination. If the character cannot reach the destination it will try to move as close as possible to it.
This value will update immediately if the destination property is changed, or if the agent is moved using the position property or the Teleport method.
If the agent has no path, or if the current path is stale (e.g. if the graph has been updated close to the agent, and it hasn't had time to recalculate its path), this will return positive infinity.
The entity internally always treats the Z axis as forward, but this property respects the orientation field. So it will return either a rotation with the Y axis as forward, or Z axis as forward, depending on the orientation field.
Note
if updateRotation is true (which is the default), this will also set the transform's rotation. If updateRotation is false, only the agent's internal rotation will be set.
This will return the agent's rotation even if updateRotation is false.
How much to smooth the visual rotation of the agent.
Public
float
rotationSmoothing
How much to smooth the visual rotation of the agent.
This does not affect movement, but smoothes out how the agent rotates visually.
Recommended values are between 0.0 and 0.5. A value of zero will disable smoothing completely.
The smoothing is done primarily using an exponential moving average, but with a small linear term to make the rotation converge faster when the agent is almost facing the desired direction.
Adding smoothing will make the visual rotation of the agent lag a bit behind the actual rotation. Too much smoothing may make the agent seem sluggish, and appear to move sideways.
The unit for this field is seconds.
rotationSpeed
Desired rotation speed in degrees per second.
Public
float
rotationSpeed
Desired rotation speed in degrees per second.
If the agent is in an open area and gets a new destination directly behind itself, it will start to rotate around with exactly this rotation speed.
The agent will slow down its rotation speed as it approaches its desired facing direction. So for example, when it is only 90 degrees away from its desired facing direction, it will only rotate with about half this speed.
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.
stopDistance
How far away from the destination should the agent aim to stop, in world units.
Public
float
stopDistance
How far away from the destination should the agent aim to stop, in world units.
If the agent is within this distance from the destination point it will be considered to have reached the destination.
Even if you want the agent to stop precisely at a given point, it is recommended to keep this slightly above zero. If it is exactly zero, the agent may have a hard time deciding that it has actually reached the end of the path, due to floating point errors and such.
Note
This will not be multiplied the agent's scale.
updatePosition
Determines if the character's position should be coupled to the Transform's position.
Public
bool
updatePosition
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 GameObject that this component is attached to will not move. Instead, only the position property and the internal entity's position will change.
This is useful if you want to control the movement of the character using some other means, such as root motion, but still want the AI to move freely.
See
canMove which in contrast to this field will disable all movement calculations.
Determines if the character's rotation should be coupled to the Transform's rotation.
Public
bool
updateRotation
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 GameObject that this component is attached to will not rotate. Instead, only the rotation property and the internal entity's rotation will change.
This is particularly useful for 2D games where you want the Transform to stay in the same orientation, and instead swap out the displayed sprite to indicate the direction the character is facing.
You can enable PIDMovement.DebugFlags.Rotation in debugFlags to draw a gizmos arrow in the scene view to indicate the agent's internal rotation.
the rotation that the agent wants to rotate to during this frame.
)
Calculate how the character wants to move 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: void Update () { // Disable the AIs own movement code ai.canMove = false; Vector3 nextPosition; Quaternion nextRotation; // Calculate how the AI wants to move ai.MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation); // Modify nextPosition and nextRotation in any way you wish // Actually move the AI ai.FinalizeMovement(nextPosition, nextRotation); }
OnDisable
()
Called when the component is disabled or about to be destroyed.
Private
void
OnDisable ()
Called when the component is disabled or about to be destroyed.
This is also called by Unity when an undo/redo event is performed. This means that when an undo event happens the entity will get destroyed and then re-created.