Flocking
Birds, fish, bats, zombie hordes, a swarm of drones: none of them has a leader planning the group's route, yet the group moves as one. Craig Reynolds showed in 1987 ("boids") that three local rules, each looking only at nearby neighbours, are enough:
| Rule | Steers toward | Effect |
|---|---|---|
| Separation | away from neighbours that are too close | no stacking, personal space |
| Alignment | the neighbours' average heading | everyone ends up flying the same way |
| Cohesion | the neighbours' average position | the group stays together |
Each rule is a steering force, and the flock is just their weighted sum (see combining behaviors). Nobody knows the shape of the whole flock; it emerges.
A flock in numbers
The program starts eight boids scattered with mixed headings in a 20 × 20 world that wraps around at the edges. Every few steps it prints two measures of "flockness":
- order: the length of the average unit heading. 0 means everyone flies in different directions, 1 means perfectly aligned.
- spread: the average distance from the flock's centre.
using System;
using System.Linq;
uint seed = 7;
double Next() { seed = seed * 1664525u + 1013904223u; return (seed >> 8) / 16777216.0; } // [0, 1)
const int N = 8;
const double Size = 20, Radius = 6, MaxSpeed = 2, MaxForce = 3;
var pos = new V2[N];
var vel = new V2[N];
for (int i = 0; i < N; i++)
{
pos[i] = new V2(6 + Next() * 8, 6 + Next() * 8);
double a = Next() * 2 * Math.PI;
vel[i] = new V2(Math.Cos(a), Math.Sin(a)) * MaxSpeed;
}
for (int step = 0; step <= 120; step++)
{
if (step % 20 == 0) Report(step);
var force = new V2[N];
for (int i = 0; i < N; i++)
{
V2 sep = new(0, 0), avgVel = new(0, 0), centre = new(0, 0);
int count = 0;
for (int j = 0; j < N; j++)
{
if (j == i) continue;
V2 d = Wrap(pos[j] - pos[i]); // shortest offset in the wrapping world
double dist = d.Len;
if (dist > Radius) continue;
count++;
avgVel += vel[j];
centre += d; // centre relative to me
if (dist < 2 && dist > 1e-6) sep -= d.Norm() * (2 - dist);
}
if (count == 0) continue;
V2 align = (avgVel * (1.0 / count)).Norm() * MaxSpeed - vel[i];
V2 cohere = (centre * (1.0 / count)).Norm() * MaxSpeed - vel[i];
force[i] = sep * 2.0 + align * 1.0 + cohere * 0.4;
}
for (int i = 0; i < N; i++) // apply after all forces are known
{
vel[i] = (vel[i] + force[i].Clamp(MaxForce) * 0.1).Clamp(MaxSpeed);
pos[i] = new V2(Mod(pos[i].X + vel[i].X * 0.1), Mod(pos[i].Y + vel[i].Y * 0.1));
}
}
void Report(int step)
{
V2 heading = new(0, 0);
foreach (var v in vel) heading += v.Norm();
double order = heading.Len / N;
V2 c = pos[0]; // centre measured around boid 0 (wrap-safe)
V2 sum = new(0, 0);
foreach (var p in pos) sum += Wrap(p - pos[0]);
c += sum * (1.0 / N);
double spread = pos.Average(p => Wrap(p - c).Len);
Console.WriteLine(quot;step {step,3}: order {order:F2} spread {spread:F2} boid0 at {pos[0]}");
}
static double Mod(double x) => ((x % Size) + Size) % Size;
static V2 Wrap(V2 d) => new(d.X - Size * Math.Round(d.X / Size), d.Y - Size * Math.Round(d.Y / Size));
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)})";
}step 0: order 0.37 spread 3.47 boid0 at (7.91, 13.31)
step 20: order 0.94 spread 4.01 boid0 at (5.80, 12.05)
step 40: order 0.99 spread 3.87 boid0 at (4.01, 9.98)
step 60: order 0.91 spread 2.98 boid0 at (2.47, 7.13)
step 80: order 0.97 spread 2.04 boid0 at (1.27, 4.16)
step 100: order 0.99 spread 1.80 boid0 at (19.56, 1.61)
step 120: order 1.00 spread 1.73 boid0 at (17.86, 19.27)
Order climbs from 0.37 to 1.00 as the boids agree on a direction, and the spread settles around 1.7 units: cohesion pulls them together, separation stops it collapsing to zero. Boid 0 leaves the left edge after step 80 and reappears on the right, which is why the neighbour offsets go through Wrap. Try setting the alignment weight to 0: the boids still clump (cohesion) but drift in different directions, and order stays low.
Note: The neighbour loop is O(n²). Fine for 8 or 80 boids, too slow for 5,000. Real flocks put boids into a spatial hash grid (cells the size of the neighbour radius) and only check the 3 × 3 cells around each boid. Large crowd systems in engines use the same kind of spatial partitioning.
Watch it, steer it
Click the frame. The boids flock around the canvas and are drawn toward the pointer while it's over the frame. Toggle the rules with S (separation), A (alignment) and C (cohesion) and watch how each one changes the group.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
const N = 60, RADIUS = 40, MAX_SPEED = 90, MAX_FORCE = 140;
const rules = { sep: true, ali: true, coh: true };
const pointer = { x: 0, y: 0, inside: false };
let s = 12345;
const rnd = () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); // seeded, so every reload looks the same
const boids = Array.from({ length: N }, () => {
const a = rnd() * Math.PI * 2;
return { x: rnd() * W, y: rnd() * H, vx: Math.cos(a) * MAX_SPEED, vy: Math.sin(a) * MAX_SPEED };
});
cv.addEventListener('pointermove', (e) => {
const r = cv.getBoundingClientRect();
pointer.x = (e.clientX - r.left) * (W / r.width);
pointer.y = (e.clientY - r.top) * (H / r.height);
pointer.inside = true;
});
cv.addEventListener('pointerleave', () => { pointer.inside = false; });
function wrapD(d, size) { return d - size * Math.round(d / size); }
function limit(x, y, m) { const l = Math.hypot(x, y); return l > m ? [x / l * m, y / l * m] : [x, y]; }
function update(dt) {
if (pressed.has('KeyS')) rules.sep = !rules.sep;
if (pressed.has('KeyA')) rules.ali = !rules.ali;
if (pressed.has('KeyC')) rules.coh = !rules.coh;
const forces = boids.map((b) => {
let sx = 0, sy = 0, ax = 0, ay = 0, cx = 0, cy = 0, n = 0;
for (const o of boids) {
if (o === b) continue;
const dx = wrapD(o.x - b.x, W), dy = wrapD(o.y - b.y, H), d = Math.hypot(dx, dy);
if (d > RADIUS) continue;
n++; ax += o.vx; ay += o.vy; cx += dx; cy += dy;
if (d < 16 && d > 0) { sx -= dx / d * (16 - d); sy -= dy / d * (16 - d); }
}
let fx = 0, fy = 0;
if (n) {
const al = Math.hypot(ax, ay) || 1, cl = Math.hypot(cx, cy) || 1;
if (rules.sep) { fx += sx * 6; fy += sy * 6; }
if (rules.ali) { fx += ax / al * MAX_SPEED - b.vx; fy += ay / al * MAX_SPEED - b.vy; }
if (rules.coh) { fx += (cx / cl * MAX_SPEED - b.vx) * 0.4; fy += (cy / cl * MAX_SPEED - b.vy) * 0.4; }
}
if (pointer.inside) {
const dx = pointer.x - b.x, dy = pointer.y - b.y, d = Math.hypot(dx, dy) || 1;
fx += (dx / d * MAX_SPEED - b.vx) * 0.3; fy += (dy / d * MAX_SPEED - b.vy) * 0.3;
}
return limit(fx, fy, MAX_FORCE);
});
boids.forEach((b, i) => {
[b.vx, b.vy] = limit(b.vx + forces[i][0] * dt, b.vy + forces[i][1] * dt, MAX_SPEED);
b.x = (b.x + b.vx * dt + W) % W;
b.y = (b.y + b.vy * dt + H) % H;
});
}
function draw() {
ctx.fillStyle = '#0e1018'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#80deea';
for (const b of boids) {
ctx.save(); ctx.translate(b.x, b.y); ctx.rotate(Math.atan2(b.vy, b.vx));
ctx.beginPath(); ctx.moveTo(7, 0); ctx.lineTo(-5, 4); ctx.lineTo(-5, -4); ctx.closePath(); ctx.fill();
ctx.restore();
}
ctx.fillStyle = '#ccc'; ctx.font = '13px system-ui, sans-serif';
const on = (k) => (rules[k] ? 'on' : 'off');
ctx.fillText(`S separation ${on('sep')} A alignment ${on('ali')} C cohesion ${on('coh')}`, 10, 18);
}
run(update, draw, 'S / A / C toggle the three rules; the pointer attracts the flock');
</script>Flocking in games
- Ambient life: birds, fish, insects, crowds of civilians. Cheap, convincing, and nobody inspects it closely.
- Hordes and swarms: zombies or drones that should surround the player rather than queue behind each other. Add a seek or pursuit force toward the player to the three rules.
- Formations-lite: a squad that should move "together" but not in a rigid formation. For tight formations, give each member a slot relative to a leader instead (see Squad Coordination).
- Combined with pathfinding: one path (or one flow field) for the whole group, with flocking forces keeping members apart and together along it.
Tip: Limit the neighbour count as well as the radius (for example, the 6 nearest). Field studies of starling flocks found that each bird tracks only its six or seven nearest neighbours, and capping the count keeps the cost per boid constant when the flock gets dense.
Test yourself
Which of the three boid rules makes the flock fly in a common direction?
- Separation
- Alignment
- Cohesion
- Wander
What keeps the neighbour search from becoming the bottleneck with thousands of boids?
- A larger neighbour radius
- A spatial hash grid so each boid only checks nearby cells
- Running flocking every 10 seconds
- Sorting boids by speed
In the program, what does the 'order' value measure?
- How many boids exist
- The length of the average unit heading: 1 when all boids fly the same way
- The distance travelled
- The number of collisions