Creative Coding From Zero · Episode 09
Flocking (Boids)
Flocking (Boids) is Episode 09 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
Watch a flock of starlings at dusk and you'd swear there's a choreographer in the sky — the whole cloud folds, splits, and pours across the horizon like one enormous animal. There isn't. There's no leader, no plan, no bird that can see more than its handful of neighbors. In 1986 Craig Reynolds showed that three tiny local rules — don't crowd, fly the way your neighbors fly, drift toward the middle of your neighbors — are enough to conjure the entire spectacle out of nothing. He called his simulated birds boids, and they are the single most famous demo in all of generative art: the canonical proof that complexity is something simple rules do, not something you have to program in.
By the end of this episode you'll have a hypnotic murmuration of a few thousand agents running at a smooth 60fps, each one following only what's near it — and you'll steer the whole organism by dragging a predator through it and watching the flock tear open and re-form around your cursor. We'll build it the honest way: start with aimless wanderers, add the three rules one at a time so you can feel each one click into place, then drop in the one data structure — a spatial-hash grid — that takes us from a few hundred boids to a few thousand without dropping a frame. No leader. No magic. Just neighbors.
What you're looking at
Every triangle on that canvas is a boid: a point with a position and a velocity, pointed in the direction it's moving. On its own it knows almost nothing — it can't see the whole flock, doesn't know where the edges are, has no goal. Each frame it looks at the boids inside a small circle around itself (its vision radius), computes three little steering nudges from them, adds those nudges to its velocity, and moves. That's the entire program. There is no array that stores "the flock" as a shape; the shape is what emerges when a couple thousand of these selfish little triangles all run the same three rules at once.
Step the stage selector from 1 to 6 to build the behavior up one layer at a time, and grab the sliders — especially the three weight sliders — to feel how delicately the look depends on their balance. Crank cohesion to the top and the flock collapses into a quivering blob; drop it to zero and the birds scatter to the wind. The sweet spot, the murmuration, lives in a narrow band you can find by ear. The seed field plus regenerate reseeds the initial scatter of boids deterministically — the same seed always lays them out identically, so a configuration you like is reproducible.
Stage 1 — Wandering agents
Before any flocking, just the substrate: a swarm of points that move and wrap. Each boid starts at a seeded-random position with a seeded-random velocity, and every frame we add velocity to position. When one slides off the right edge it reappears on the left — the world is a torus, a screen that wraps around on itself, so nobody ever piles up against a wall. There are no rules yet, so the motion is pure Brownian drift: a TV-static snowstorm of triangles, each minding its own business. Boring on purpose. This is the blank canvas the three rules will paint on, and it's worth seeing how uncoordinated it looks so the first rule lands with a jolt.
Stage 2 — + Separation
The first rule, and the one that keeps the simulation from looking like a single fused glob: don't crowd your neighbors. For every boid closer than a small personal-space radius, steer directly away from it — and weight the push by how close it is, so a boid about to collide shoves hard while a distant one barely registers. Turn this on alone and the snowstorm suddenly has texture: the points repel into a loose, evenly-spaced gas, like beads of oil refusing to touch. Separation is what gives a flock its airy, never-quite-colliding quality. Without it, cohesion (Stage 4) would suck every bird into the same pixel.
Stage 3 — + Alignment
Now they start to agree. Alignment says: look at the boids near you, average their velocities, and steer to match that average heading. One boid copying its neighbors does nothing; a whole field of boids each copying their neighbors produces flow — rivers and currents of triangles all sweeping the same way, splitting around invisible obstacles and merging again. This is the rule that turns a gas into a school of fish. Watch how a direction, once a few boids commit to it, propagates outward like a rumor: alignment is local, but its effect ripples across the entire swarm.
Stage 4 — + Cohesion → full flocking
The third and final rule closes the loop: cohesion — steer toward the average position of your neighbors, the local center of mass. Separation pushes apart, cohesion pulls together, and the tension between those two opposing forces is exactly what makes a flock hang together as a body while staying loose enough to breathe. With all three rules live you have real flocking: cohesive blobs that don't collapse, shared headings that turn as one, and that uncanny living quality where the whole cloud seems to think. Three rules. No leader. Reynolds nailed it in '86 and nobody has needed to add a fourth.
Stage 5 — Spatial-hash grid (the perf trick)
Here's the catch nobody tells you in the pretty videos. The naive way to find "boids
near me" is to loop over every other boid and check the distance — which is
O(N²). At 200 boids that's 40,000 checks a frame: fine. At 2,000 boids it's
four million checks a frame, sixty times a second, and your fps falls
off a cliff. The fix is a spatial-hash grid: chop the world into square
cells (one vision-radius wide), drop each boid into its cell, and when a boid asks "who's
near me?" only check the nine cells touching it instead of the whole world. This single
data structure is the difference between a toy and a murmuration — flip to this stage and
push the boid slider to 4,000 and watch the fps counter not move.
Stage 6 — Styled: trails, color, and a predator
Same simulation, dressed for the screen. Instead of clearing the canvas to black each frame we paint a translucent black rectangle over it, so old positions fade out slowly and every boid drags a comet-tail of motion behind it — the trick that turns a swarm into silk. Each boid is colored by its heading and speed via a cosine palette, so currents flowing different directions glow in different hues and the flow structure becomes visible as color. And there's a predator: your mouse. Any boid that sees the cursor inside its panic radius drops everything and flees, hard — so dragging through the flock tears a void open around your pointer and the murmuration boils and re-forms in your wake. This is the frame-worthy version; the rest was scaffolding.
How the code works
A boid is just four numbers: position (x, y) and velocity
(vx, vy). We keep them in flat typed arrays — one Float32Array
for x, one for y, and so on — because that's cache-friendly and lets us scale to
thousands without garbage-collector hitches. The seeded RNG (mulberry32,
from the series brief) lays out the initial scatter, so a given seed always reproduces
the same starting flock.
(a) The boid update — three steering forces, summed and weighted. This is the whole brain. For one boid we walk its neighbors, accumulate the three behaviors, normalize each to a steering force (desired velocity minus current velocity — this is the crucial bit), scale by the user weights, and add the result to velocity:
// For boid i: gather the three behaviors from neighbors within vision.
let sepX=0, sepY=0; // steer away from close ones
let aliX=0, aliY=0, aliN=0; // average neighbor velocity
let cohX=0, cohY=0, cohN=0; // average neighbor position
forEachNeighbor(i, (j, dx, dy, d2) => { // dx,dy = j - i; d2 = dist²
if (d2 < sepR2 && d2 > 0) { // SEPARATION: push from very close
const inv = 1 / d2; // closer ⇒ stronger
sepX -= dx * inv; sepY -= dy * inv;
}
aliX += vx[j]; aliY += vy[j]; aliN++; // ALIGNMENT: sum velocities
cohX += x[j]; cohY += y[j]; cohN++; // COHESION: sum positions
});
let ax = 0, ay = 0; // total acceleration this frame
ax += steer(sepX, sepY, vx[i], vy[i]) * wSep; // each rule →
if (aliN) ax += steer(aliX/aliN, aliY/aliN, vx[i], vy[i]) * wAli; // a steering
if (cohN) ax += steer(cohX/cohN - x[i], cohY/cohN - y[i], vx[i], vy[i]) * wCoh; // force
// (ay accumulated the same way with the Y components)
The steer() helper is the heart of "steering vs. setting velocity." It
takes a desired direction, scales it to the boid's max speed, subtracts the
current velocity, and clamps the result to a max force. Returning the
difference — not the desired velocity itself — is what makes turns gradual and
organic instead of instantaneous and twitchy. It also quietly guards against the classic
NaN bug:
// Turn a desired direction into a clamped steering force.
function steer(dx, dy, vx, vy) {
const m = Math.hypot(dx, dy);
if (m === 0) return [0, 0]; // normalize(0)=NaN — guard it!
const s = MAX_SPEED / m; // scale dir to max speed
let fx = dx * s - vx, fy = dy * s - vy; // desired − current = steering
const fm = Math.hypot(fx, fy); // clamp to max force
if (fm > MAX_FORCE) { const k = MAX_FORCE / fm; fx *= k; fy *= k; }
return [fx, fy];
}
(b) The spatial-hash grid. Each frame we rebuild a grid keyed by cell coordinate. Cell size equals the vision radius, so every neighbor a boid cares about lives in its own cell or one of the eight around it — nine cells total, regardless of how many thousand boids exist:
const cell = vision; // one cell = one vision radius
const cols = Math.ceil(W / cell), rows = Math.ceil(H / cell);
const grid = new Array(cols * rows); // each slot: array of boid indices
function rebuild() {
for (let c = 0; c < grid.length; c++) grid[c] = grid[c] ? (grid[c].length = 0, grid[c]) : [];
for (let i = 0; i < N; i++) {
const cx = (x[i] / cell) | 0, cy = (y[i] / cell) | 0;
grid[cy * cols + cx].push(i); // drop boid into its cell
}
}
// Visit only the 3×3 block of cells around boid i.
function forEachNeighbor(i, fn) {
const cx = (x[i] / cell) | 0, cy = (y[i] / cell) | 0;
for (let gy = cy - 1; gy <= cy + 1; gy++)
for (let gx = cx - 1; gx <= cx + 1; gx++) {
const bucket = grid[wrapRow(gy) * cols + wrapCol(gx)]; // wrap cells too
for (let k = 0; k < bucket.length; k++) {
const j = bucket[k]; if (j === i) continue;
let dx = x[j]-x[i], dy = y[j]-y[i];
// toroidal wrap: take the shortest path across the seam
if (dx > W/2) dx -= W; else if (dx < -W/2) dx += W;
if (dy > H/2) dy -= H; else if (dy < -H/2) dy += H;
const d2 = dx*dx + dy*dy;
if (d2 < vision*vision) fn(j, dx, dy, d2); // circle, not square
}
}
}
(c) Wrap + heading. After integrating velocity into position we
wrap each coordinate into [0, W) with a modulo, so the world is seamless.
Drawing the boid as a little triangle just needs the heading, which is
atan2(vy, vx) — the direction the velocity points:
// integrate, then wrap into the torus
x[i] += vx[i]; y[i] += vy[i];
x[i] = (x[i] % W + W) % W; // % can go negative — the +W fixes it
y[i] = (y[i] % H + H) % H;
// draw a triangle pointing along the velocity
const ang = Math.atan2(vy[i], vx[i]); // heading from velocity
ctx.translate(x[i], y[i]); ctx.rotate(ang);
ctx.beginPath();
ctx.moveTo(6, 0); ctx.lineTo(-4, 3); ctx.lineTo(-4, -3); ctx.closePath();
ctx.fill();
(d) The predator flee. The mouse is a single extra agent the boids fear. If a boid sees the cursor within its panic radius, we add one more steering force — away from the predator, scaled up so it overrides the gentle flocking — and that's all it takes to carve a hole through the murmuration:
// predator at (px,py): flee hard if it's inside panic radius
if (predatorOn) {
let dx = x[i] - px, dy = y[i] - py; // away from the cursor
const d2 = dx*dx + dy*dy;
if (d2 < PANIC*PANIC && d2 > 0) {
const [fx, fy] = steer(dx, dy, vx[i], vy[i]);
ax += fx * 4.5; ay += fy * 4.5; // fear > flocking
}
}
Wire those four pieces together — rebuild the grid, run the update over every boid, integrate-and-wrap, draw — and the loop runs itself. Nothing in here knows what a "flock" is.
Common pitfalls
- O(N²) neighbor search kills fps. The single biggest trap. Looping every boid against every other boid is quadratic and dies around a thousand agents. Build the spatial-hash grid (Stage 5) before you scale up, not after you've already given up on big flocks. With the grid, neighbor queries are effectively constant-time per boid.
- Weight balance is a knife-edge. Too much cohesion and the flock implodes into a single jittering blob; too much separation and it boils apart into static; too much alignment and it freezes into a rigid sheet. There's no "correct" number — tune the three weights by eye until it looks alive. The defaults here (sep 1.5, ali 1.0, coh 1.0) are a good starting basin.
normalize(0) = NaN. When a boid has no neighbors, or sits exactly on a neighbor, a steering vector can have zero length — and dividing by that length producesNaN, which poisons the position and the boid vanishes forever (and often takes the whole sim with it). Always guard:if (mag === 0) returnbefore normalizing.- Wrap-around at the edges. Two gotchas. First, JavaScript's
%can return negatives, so wrap with(p % W + W) % W, not a barep % W. Second, when measuring distance on a torus you must take the shortest path across the seam (thedx > W/2correction above), or boids near an edge will ignore neighbors that are visually right next to them on the other side. - Steering vs. setting velocity. The rookie move is to set a boid's velocity straight to the desired direction. That makes it snap instantly and look robotic. The Reynolds trick is to compute desired − current as a small force and add it, then clamp speed — so the boid turns smoothly. Force, not teleport.
Exercises
- Obstacles to avoid. Drop a few static circles into the world and add a fourth steering force that pushes boids away from any obstacle within range (same shape as the predator flee, but the obstacle doesn't move). Watch the flock braid itself around the pillars — this is how Reynolds' boids navigate environments.
- Multiple species. Give each boid a
speciesid and a color. Make alignment and cohesion only count same-species neighbors, while separation still applies to everyone. You'll get two flocks that interpenetrate but refuse to merge — instant ecosystem. - A food source they swarm. Add a slowly-drifting food point and a weak attraction toward it (the inverse of the predator). Tune it so the flock orbits the food like bees around a flower instead of collapsing onto it — the orbit is the balance of attraction against separation. Bonus: let the food teleport on click.
What's next
Episode 10 — Cellular Automata: the art in simple rules. Boids put the agents in continuous space and let them steer; cellular automata snap everything to a grid and let cells flip on or off based purely on their neighbors. Same big idea — complexity from trivial local rules — but a completely different aesthetic: Conway's Life, cyclic CAs, and reaction-diffusion patterns that look like coral, fingerprints, and leopard spots, all from a one-line update applied to a grid of pixels.