Imagine you’re building a game in Unity and you want an AI-controlled character to chase a target, dodging obstacles on its way. The usual answer is Unity’s NavMesh. But what if you want full control over how the AI moves and avoids things? In this post we’ll build a small custom AI controller that does exactly that, and look at how each part of it works.
Written for Unity 6. It uses
Rigidbody.linearVelocity, which Unity 6 introduced (older versions call itvelocity).
Setting up the scene
A flat ground, a few obstacles (cubes or other shapes), an AI character (a capsule) and a target (a sphere) for the AI to chase.

How it works
Every physics step the AI adds up three directions and turns toward the result:
- The target: where it wants to go.
- Nearby obstacles: a push away from everything inside a small radius around it.
- Obstacles ahead: three rays (forward, forward-left, forward-right) look ahead and steer it around what they hit.

The settings
[SerializeField] private Transform Target; // The target to chase
[SerializeField] private float MoveSpeed = 5f; // Top speed
[SerializeField] private float RotationSpeed = 10f; // How fast the AI turns
[SerializeField] private float ObstacleAvoidanceRadius = 2f; // Radius to detect nearby obstacles
[SerializeField] private float RaycastDistance = 3f; // How far ahead to look for collisions
[SerializeField] private float RaycastAvoidanceForce = 5f; // Strength of the raycast avoidance
[SerializeField] private LayerMask ObstacleLayer; // Obstacles only: not the AI, not the ground
They are private fields with [SerializeField], so you can tweak them in the Inspector without making them public.
Initialization
In Awake we grab the Rigidbody, freeze its rotation so physics never tips the AI over, and turn on interpolation so the movement looks smooth on screen, even though it only changes in physics steps.
private void Awake()
{
m_Rigidbody = GetComponent<Rigidbody>();
m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotation; // No tipping over
m_Rigidbody.interpolation = RigidbodyInterpolation.Interpolate; // Smooth movement on screen
m_CurrentSpeed = MoveSpeed;
}
The core logic: FixedUpdate
FixedUpdate runs at a fixed interval, in step with physics, which is where Rigidbody code belongs. Inside it we read the Rigidbody’s own position and rotation rather than the Transform’s, because with interpolation on the Transform shows a smoothed in-between pose.
Direction to the target
if (Target == null) return;
var toTarget = Flatten(Target.position - m_Rigidbody.position).normalized;
Flatten sets y to zero. The AI only steers on the ground plane: if the target sits higher or lower (a sphere floating above the floor, for example), an unflattened direction would tilt the AI’s nose into the ground or the air.
private static Vector3 Flatten(Vector3 vector)
{
vector.y = 0f;
return vector;
}
Avoiding nearby obstacles
var avoidance = AvoidObstacles();
AvoidObstacles finds every obstacle within ObstacleAvoidanceRadius with Physics.OverlapSphereNonAlloc (no garbage, it fills an array we keep), and adds up a push away from each one. The push is divided by the distance, so closer obstacles push harder.
private Vector3 AvoidObstacles()
{
var avoidance = Vector3.zero;
var position = m_Rigidbody.position;
var count = Physics.OverlapSphereNonAlloc(position, ObstacleAvoidanceRadius, m_ObstacleColliders, ObstacleLayer);
for (var i = 0; i < count; i++)
{
// ClosestPoint works with Box, Sphere, Capsule and convex Mesh colliders
var away = Flatten(position - m_ObstacleColliders[i].ClosestPoint(position));
avoidance += away.normalized / Mathf.Max(away.magnitude, MinDistance);
}
return avoidance;
}
Mathf.Max(..., MinDistance) matters: when the AI touches an obstacle the distance is zero, and dividing by zero gives NaN, which breaks the rotation for good.
Predicting collisions
var prediction = PredictCollisions(toTarget);
PredictCollisions casts three rays ahead. For every hit it pushes away along the surface normal, and also slides along the wall. The slide is the important part: when a wall is straight ahead, the normal points straight back at the AI and cancels its wish to reach the target, so with the normal alone the AI just stops and shakes in front of the wall.
The slide keeps the side the AI is already turning toward. If it picked the side closer to the target instead, the choice would flip every time the AI moved a little and it would swing left and right in front of the wall forever.
// Forward, forward-right and forward-left, in local space
private static readonly Vector3[] RayDirections =
{
Vector3.forward,
new Vector3(1f, 0f, 1f).normalized,
new Vector3(-1f, 0f, 1f).normalized,
};
private Vector3 PredictCollisions(Vector3 toTarget)
{
var avoidance = Vector3.zero;
var position = m_Rigidbody.position;
foreach (var localDirection in RayDirections)
{
var direction = m_Rigidbody.rotation * localDirection;
if (!Physics.Raycast(position, direction, out var hit, RaycastDistance, ObstacleLayer)) continue;
var normal = Flatten(hit.normal).normalized;
if (normal == Vector3.zero) continue;
// Slide along the wall, the way the AI already faces (toward the target on a perfect head-on hit)
var along = Vector3.Cross(Vector3.up, normal);
var facing = m_Rigidbody.rotation * Vector3.forward;
var side = Vector3.Dot(along, facing);
if (side < 0f || (Mathf.Abs(side) < 0.05f && Vector3.Dot(along, toTarget) < 0f)) along = -along;
avoidance += (normal + along).normalized * RaycastAvoidanceForce / Mathf.Max(hit.distance, MinDistance);
}
return avoidance;
}
The ray directions live in a static readonly array, so nothing is allocated every physics step.
Turning and moving
We add the three directions together, turn toward the result with Quaternion.Slerp, and move forward.
var finalDirection = Flatten(toTarget + avoidance + prediction);
if (finalDirection.sqrMagnitude > 0.01f)
{
var targetRotation = Quaternion.LookRotation(finalDirection.normalized);
m_Rigidbody.MoveRotation(Quaternion.Slerp(m_Rigidbody.rotation, targetRotation, RotationSpeed * Time.fixedDeltaTime));
}
// Move forward, but keep the vertical velocity so gravity still works
var velocity = m_Rigidbody.rotation * Vector3.forward * m_CurrentSpeed;
velocity.y = m_Rigidbody.linearVelocity.y;
m_Rigidbody.linearVelocity = velocity;
Two details are easy to get wrong here:
- Rotate through the Rigidbody with
MoveRotation. Settingtransform.rotationdirectly fights the physics engine, andFreezeRotationdoes not stop it, because the constraint only blocks rotation that comes from physics. - Keep the vertical velocity. Writing
linearVelocity = forward * speedresets the falling speed every step, so the AI floats and never lands. Copyingyfrom the current velocity keeps gravity working, and the AI can walk down slopes and off ledges.
Slowing down near obstacles
A chaser that takes corners at full speed looks clumsy. We keep a separate m_CurrentSpeed, ease it down to half of MoveSpeed while either kind of avoidance is active, and back up once the way is clear. MoveSpeed itself stays what you set in the Inspector.
var avoiding = avoidance.sqrMagnitude + prediction.sqrMagnitude > 0.01f;
m_CurrentSpeed = Mathf.Lerp(m_CurrentSpeed, avoiding ? MoveSpeed * 0.5f : MoveSpeed, Time.fixedDeltaTime);
Seeing it in the editor
OnDrawGizmos draws the avoidance radius and the three rays in the Scene view, which makes tuning the numbers much easier.
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, ObstacleAvoidanceRadius);
Gizmos.color = Color.blue;
foreach (var localDirection in RayDirections)
{
Gizmos.DrawRay(transform.position, transform.rotation * localDirection * RaycastDistance);
}
}
The full script
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class AIController : MonoBehaviour
{
[SerializeField] private Transform Target; // The target to chase
[SerializeField] private float MoveSpeed = 5f; // Top speed
[SerializeField] private float RotationSpeed = 10f; // How fast the AI turns
[SerializeField] private float ObstacleAvoidanceRadius = 2f; // Radius to detect nearby obstacles
[SerializeField] private float RaycastDistance = 3f; // How far ahead to look for collisions
[SerializeField] private float RaycastAvoidanceForce = 5f; // Strength of the raycast avoidance
[SerializeField] private LayerMask ObstacleLayer; // Obstacles only: not the AI, not the ground
private const float MinDistance = 0.01f; // Never divide by zero when touching an obstacle
// Forward, forward-right and forward-left, in local space
private static readonly Vector3[] RayDirections =
{
Vector3.forward,
new Vector3(1f, 0f, 1f).normalized,
new Vector3(-1f, 0f, 1f).normalized,
};
private readonly Collider[] m_ObstacleColliders = new Collider[16];
private Rigidbody m_Rigidbody;
private float m_CurrentSpeed;
private void Awake()
{
m_Rigidbody = GetComponent<Rigidbody>();
m_Rigidbody.constraints = RigidbodyConstraints.FreezeRotation; // No tipping over
m_Rigidbody.interpolation = RigidbodyInterpolation.Interpolate; // Smooth movement on screen
m_CurrentSpeed = MoveSpeed;
}
private void FixedUpdate()
{
if (Target == null) return;
var toTarget = Flatten(Target.position - m_Rigidbody.position).normalized;
var avoidance = AvoidObstacles();
var prediction = PredictCollisions(toTarget);
// Turn toward the combined direction
var finalDirection = Flatten(toTarget + avoidance + prediction);
if (finalDirection.sqrMagnitude > 0.01f)
{
var targetRotation = Quaternion.LookRotation(finalDirection.normalized);
m_Rigidbody.MoveRotation(Quaternion.Slerp(m_Rigidbody.rotation, targetRotation, RotationSpeed * Time.fixedDeltaTime));
}
// Slow down to half speed while avoiding something, speed back up when the way is clear
var avoiding = avoidance.sqrMagnitude + prediction.sqrMagnitude > 0.01f;
m_CurrentSpeed = Mathf.Lerp(m_CurrentSpeed, avoiding ? MoveSpeed * 0.5f : MoveSpeed, Time.fixedDeltaTime);
// Move forward, but keep the vertical velocity so gravity still works
var velocity = m_Rigidbody.rotation * Vector3.forward * m_CurrentSpeed;
velocity.y = m_Rigidbody.linearVelocity.y;
m_Rigidbody.linearVelocity = velocity;
}
// Pushes away from every obstacle inside the avoidance radius; closer obstacles push harder.
private Vector3 AvoidObstacles()
{
var avoidance = Vector3.zero;
var position = m_Rigidbody.position;
var count = Physics.OverlapSphereNonAlloc(position, ObstacleAvoidanceRadius, m_ObstacleColliders, ObstacleLayer);
for (var i = 0; i < count; i++)
{
// ClosestPoint works with Box, Sphere, Capsule and convex Mesh colliders
var away = Flatten(position - m_ObstacleColliders[i].ClosestPoint(position));
avoidance += away.normalized / Mathf.Max(away.magnitude, MinDistance);
}
return avoidance;
}
// Looks ahead with raycasts and steers around what they hit.
private Vector3 PredictCollisions(Vector3 toTarget)
{
var avoidance = Vector3.zero;
var position = m_Rigidbody.position;
foreach (var localDirection in RayDirections)
{
var direction = m_Rigidbody.rotation * localDirection;
if (!Physics.Raycast(position, direction, out var hit, RaycastDistance, ObstacleLayer)) continue;
var normal = Flatten(hit.normal).normalized;
if (normal == Vector3.zero) continue;
// Pushing only along the normal cancels the target direction when the wall is straight ahead,
// so also slide along the wall. Keep sliding the way the AI already faces, or it swings back and forth.
var along = Vector3.Cross(Vector3.up, normal);
var facing = m_Rigidbody.rotation * Vector3.forward;
var side = Vector3.Dot(along, facing);
if (side < 0f || (Mathf.Abs(side) < 0.05f && Vector3.Dot(along, toTarget) < 0f)) along = -along;
avoidance += (normal + along).normalized * RaycastAvoidanceForce / Mathf.Max(hit.distance, MinDistance);
}
return avoidance;
}
private static Vector3 Flatten(Vector3 vector)
{
vector.y = 0f;
return vector;
}
// Shows the avoidance radius and the rays in the Scene view.
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, ObstacleAvoidanceRadius);
Gizmos.color = Color.blue;
foreach (var localDirection in RayDirections)
{
Gizmos.DrawRay(transform.position, transform.rotation * localDirection * RaycastDistance);
}
}
}
Configuring the scene
- Create an Obstacle layer and put every obstacle on it. Keep the AI and the ground off that layer, or the AI will try to avoid itself and the floor.
- Add the AIController script to the AI character. It adds a Rigidbody for you; leave gravity on and adjust Mass, Linear Damping and Angular Damping (Unity 6’s names for Drag and Angular Drag) to taste.
- Set Obstacle Layer to the Obstacle layer, drag the target into Target, and hit Play.
Where it falls short
This is steering, not pathfinding: the AI only reacts to what is close to it. Put the target behind a U-shaped wall and it will walk into the pocket and stay there, because every way out first leads away from the target. When your levels have rooms, corridors or dead ends, use NavMesh for the route and keep a controller like this one for the last few meters and for dodging moving things.
Other things to try:
- More rays (five or seven in a wider fan) to spot obstacles earlier.
- Moving obstacles: they already work, but a faster AI needs a longer
RaycastDistanceto react in time. - Different weights for the target, the radius and the rays, to make the AI braver or more careful.