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. You do not need to know anything about ECS to be able to use it.
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. See Off-mesh links for more info.
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.
How big of a distance to try to keep from obstacles.
Typically around 1 or 2 times the agent radius is a good value for this.
Try to avoid making it so large that there might not be enough space for the agent to keep this amount of distance from obstacles. It may start to move less optimally if it is not possible to keep this distance.
This works well in open spaces, but if your game consists of a lot of tight corridors, a low, or zero value may be better.
This will be multiplied by the agent's scale to get the actual distance.
If gravity is enabled, the agent will accelerate downwards, and use a raycast to check if it should stop falling.
This has no effect if the agent's orientation is set to YAxisForward (2D mode). Gravity does not really make sense for top-down 2D games. The gravity setting is also hidden from the inspector in this mode.
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.
This is useful for, for example, selecting which animations to play, and at what speeds.
Note
Any value set here will be overriden during the next simulation step. Nevertheless, it can be useful to set this value if you have disabled the agent's movement logic using e.g. canMove. This value is only an output statistic. It is not used to control the agent's movement.
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.
Differences compared to AIPath and RichAI
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
Here are some tips for how to improve performance when using this script. As always, make sure to profile your game first, to see what is actually causing performance problems.
Disable unused features
This script has some optional parts. Local avoidance, for example. Local avoidance is used to make sure that agents do not overlap with each other. However, if you do not need it, you can disable it to improve performance.
Don't change the destination unnecessarily
Repairing the path each frame can be a significant part of the movement calculation time. The FollowerEntity will perform better if the destination is static, or moves seldom. For example, updating the destination every 10 frames will be faster than updating it every frame, but to the player, both will look basically the same.
Note
Repairing the path is different from recalculating it from scratch. The agent will recalculate the path from scratch relatively seldom, but it will repair it every frame, if necessary, to account for small changes in the agent's position and destination.
Disable debug rendering
Debug rendering has some performance costs in the Unity Editor. Disable all debugFlags and rvoSettings.debug to improve performance. However, in standalone builds, these are automatically disabled and have no cost.
Be aware of property access costs
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).
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.
This has no effect if the agent's orientation is set to YAxisForward (2D mode). Gravity does not really make sense for top-down 2D games. The gravity setting is also hidden from the inspector in this mode.
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.
This is useful for, for example, selecting which animations to play, and at what speeds.
Note
Any value set here will be overriden during the next simulation step. Nevertheless, it can be useful to set this value if you have disabled the agent's movement logic using e.g. canMove. This value is only an output statistic. It is not used to control the agent's movement.
Determines if the character's position should be coupled to the Transform's position.
Private
bool
syncPosition = 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 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.
Private
bool
syncRotation = 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 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.