TExcelTAD
Home › Game AI › Obstacle Avoidance & Separation

Obstacle Avoidance & Separation

Seek and arrive happily drive a character through a pillar or straight into its friends. Pathfinding (next section) solves the big problem of routing around walls, but locally a character still has to dodge a crate that just fell, a barrel that rolled into the corridor, or the four other guards heading for the same door. Two steering behaviors cover most of that: obstacle avoidance and separation. This lesson also shows how to combine behaviors, which is where steering gets its power.

Obstacle avoidance with a feeler

The character projects a "feeler" (a box or ray) ahead of itself, as long as the distance it will cover in the next second or so. Any obstacle whose circle overlaps that box is a threat; the nearest threat wins, and the character steers sideways, away from the obstacle's centre, harder the closer the obstacle is:

text
             obstacle
               .-.
   >=========(  o )=====    feeler (width = agent radius)
   ^           '-'
 agent        lateral offset of o from the feeler line decides which way to dodge

In local terms: forward = dot(obstacle - pos, heading) and lateral = cross(heading, obstacle - pos). The obstacle matters if 0 < forward < feelerLength and |lateral| < obstacleRadius + agentRadius.

csharp · try it yourself
using System;

var target = new V2(12, 0);
var obstacle = new V2(6, 0.3);
const double ObstacleRadius = 1.5, AgentRadius = 0.4, Margin = 0.3;

foreach (bool avoid in new[] { false, true })
{
    var v = new Vehicle(new V2(0, 0));
    double closest = double.MaxValue;
    Console.WriteLine(avoid ? "seek + avoidance:" : "seek only:");
    for (int step = 0; step <= 60; step++)
    {
        closest = Math.Min(closest, (v.Pos - obstacle).Len - ObstacleRadius - AgentRadius);
        if (step % 10 == 0) Console.WriteLine(
quot; step {step,2}: {v.Pos}"); V2 force = Seek(v, target); if (avoid) force += Avoid(v, obstacle, ObstacleRadius + AgentRadius + Margin) * 4; // weight 4 v.Apply(force, 0.1); } Console.WriteLine(closest < 0 ?
quot; went THROUGH the obstacle (overlap {-closest:F2})" :
quot; closest clearance {closest:F2}"); } static V2 Seek(Vehicle v, V2 point) => (point - v.Pos).Norm() * v.MaxSpeed - v.Vel; static V2 Avoid(Vehicle v, V2 centre, double reach) { V2 heading = v.Vel.Norm(); if (heading.Len == 0) return new V2(0, 0); double feeler = 1 + v.Vel.Len * 1.5; // look 1.5 seconds ahead V2 to = centre - v.Pos; double forward = to.X * heading.X + to.Y * heading.Y; double lateral = heading.X * to.Y - heading.Y * to.X; // > 0: obstacle is to the left if (forward < -0.5 * reach || forward > feeler || Math.Abs(lateral) >= reach) return new V2(0, 0); V2 right = new(heading.Y, -heading.X); double urgency = 1 - Math.Max(forward, 0) / feeler; // closer = stronger; keep pushing while alongside double side = lateral >= 0 ? 1 : -1; // dodge away from the centre return right * (side * v.MaxSpeed * (0.5 + urgency)); } class Vehicle(V2 pos) { public V2 Pos = pos, Vel; public double MaxSpeed = 3, MaxForce = 6; public void Apply(V2 force, double dt) { V2 accel = (force * 4).Clamp(MaxForce); Vel = (Vel + accel * dt).Clamp(MaxSpeed); Pos += Vel * dt; } } readonly record struct V2(double X, double Y) { public static V2 operator +(V2 a, V2 b) => new(a.X + b.X, a.Y + b.Y); public static V2 operator -(V2 a, V2 b) => new(a.X - b.X, a.Y - b.Y); public static V2 operator *(V2 a, double k) => new(a.X * k, a.Y * k); public double Len => Math.Sqrt(X * X + Y * Y); public V2 Norm() => Len > 1e-9 ? this * (1 / Len) : new V2(0, 0); public V2 Clamp(double max) => Len > max ? Norm() * max : this; static string F(double v) => (Math.Round(v, 2) + 0.0).ToString("F2"); public override string ToString() =>
quot;({F(X)}, {F(Y)})"; }
seek only:
  step  0: (0.00, 0.00)
  step 10: (2.29, 0.00)
  step 20: (5.28, 0.00)
  step 30: (8.28, 0.00)
  step 40: (11.28, 0.00)
  step 50: (12.60, 0.00)
  step 60: (11.82, 0.00)
  went THROUGH the obstacle (overlap 1.58)
seek + avoidance:
  step  0: (0.00, 0.00)
  step 10: (2.20, -0.38)
  step 20: (4.76, -1.58)
  step 30: (7.05, -2.32)
  step 40: (9.75, -1.09)
  step 50: (12.39, 0.19)
  step 60: (11.78, -0.11)
  closest clearance 0.28

The obstacle sits slightly above the straight line, so the avoiding vehicle dips below it and then rejoins the line to the target. Seek alone drives straight through it.

The Margin matters more than it looks. The avoidance force switches off the moment the feeler clears the circle, so with a margin of 0 the agent slides along the very edge and clips it by a few centimetres (try it). Widening the feeler by a small safety margin keeps a visible gap, and it also hides the difference between the collision shape and the art.

Note: Feelers are a local fix. A U-shaped wall or a dead end traps a purely steering agent forever. Use pathfinding for routes and steering for the last few metres and for moving obstacles. Engines do exactly this: the navmesh gives the corridor, and the agents' built-in local avoidance handles other agents (Godot's agents use RVO; Unreal offers RVO avoidance and a Detour crowd manager; Unity's NavMeshAgent has its own obstacle-avoidance settings).

Separation

Separation pushes a character away from each neighbour within a radius, with a strength that grows as they get closer (here 1 / distance). Without it, a squad sent to one point ends up stacked on a single spot, which looks broken and makes splash damage absurd:

csharp · try it yourself
using System;

var goal = new V2(10, 0);
foreach (bool separate in new[] { false, true })
{
    var squad = new[] { new Vehicle(new V2(0, -1)), new Vehicle(new V2(0, 0)), new Vehicle(new V2(0, 1)) };
    for (int step = 0; step < 80; step++)
    {
        var forces = new V2[squad.Length];
        for (int i = 0; i < squad.Length; i++)
        {
            forces[i] = Arrive(squad[i], goal, 3);
            if (separate) forces[i] += Separation(squad, i, radius: 1.5) * 2;
        }
        for (int i = 0; i < squad.Length; i++) squad[i].Apply(forces[i], 0.1);
    }
    double minGap = double.MaxValue;
    for (int i = 0; i < squad.Length; i++)
        for (int j = i + 1; j < squad.Length; j++)
            minGap = Math.Min(minGap, (squad[i].Pos - squad[j].Pos).Len);
    Console.WriteLine(
quot;{(separate ? "with separation" : "no separation ")}: " +
quot;{squad[0].Pos} {squad[1].Pos} {squad[2].Pos} closest pair {minGap:F2}"); } static V2 Arrive(Vehicle v, V2 target, double slowRadius) { V2 to = target - v.Pos; double d = to.Len; if (d < 1e-6) return v.Vel * -1; double speed = d < slowRadius ? v.MaxSpeed * d / slowRadius : v.MaxSpeed; return to * (speed / d) - v.Vel; } static V2 Separation(Vehicle[] all, int me, double radius) { V2 push = new(0, 0); for (int j = 0; j < all.Length; j++) { if (j == me) continue; V2 away = all[me].Pos - all[j].Pos; double d = away.Len; if (d > 1e-6 && d < radius) push += away.Norm() * (1 / d); // stronger when closer } return push; } class Vehicle(V2 pos) { public V2 Pos = pos, Vel; public double MaxSpeed = 3, MaxForce = 6; public void Apply(V2 force, double dt) { V2 accel = (force * 4).Clamp(MaxForce); Vel = (Vel + accel * dt).Clamp(MaxSpeed); Pos += Vel * dt; } } readonly record struct V2(double X, double Y) { public static V2 operator +(V2 a, V2 b) => new(a.X + b.X, a.Y + b.Y); public static V2 operator -(V2 a, V2 b) => new(a.X - b.X, a.Y - b.Y); public static V2 operator *(V2 a, double k) => new(a.X * k, a.Y * k); public double Len => Math.Sqrt(X * X + Y * Y); public V2 Norm() => Len > 1e-9 ? this * (1 / Len) : new V2(0, 0); public V2 Clamp(double max) => Len > max ? Norm() * max : this; static string F(double v) => (Math.Round(v, 2) + 0.0).ToString("F2"); public override string ToString() =>
quot;({F(X)}, {F(Y)})"; }
no separation  : (10.00, 0.00) (10.00, 0.00) (10.00, 0.00)  closest pair 0.00
with separation: (9.53, -0.79) (10.91, 0.00) (9.53, 0.79)  closest pair 1.58

All forces are computed first and applied afterwards, so every agent reacts to the same snapshot of positions. Updating agents one by one while others read their new positions makes the result depend on list order, a classic source of "it only breaks with this many enemies" bugs.

Combining behaviors

Method How Good for Pitfall
Weighted sum Σ weightᵢ · forceᵢ, then clamp flocks, crowds, smooth blends strong forces cancel out (a wall straight ahead, the goal straight behind it) and the agent stalls
Priority try behaviors in order (avoid → separate → seek); use the first that returns a non-zero force safety first, cheap can flicker between behaviors at a boundary
Prioritized weighted sum add forces in priority order until the MaxForce "budget" is used up most robust; what Buckland's Programming Game AI by Example recommends slightly more code

Whatever you pick, draw every force as a coloured line while tuning (see Debugging AI). Weight bugs are obvious on screen and invisible in numbers.

Test yourself

In feeler-based obstacle avoidance, which obstacle is handled when several overlap the feeler?

  1. The largest
  2. The nearest along the heading
  3. The one added first
  4. All of them equally

Why compute all agents' forces before applying any of them?

  1. It is required by C#
  2. So every agent reacts to the same snapshot and the result doesn't depend on update order
  3. It uses less memory
  4. To make separation stronger

What is the main weakness of a plain weighted sum of steering forces?

  1. It is too slow
  2. Opposing forces can cancel and leave the agent stuck
  3. It can only combine two behaviors
  4. It ignores MaxSpeed