CodeRigor

LESSON

Flocking from three rules

Steer a flock with separation, alignment and cohesion, update every boid from the same old state, and test it on a wrapping torus.

A flock has no leader and no plan. Each bird reacts to the few birds near it, and the pattern appears from that. This lesson pairs with Coding Adventure: Boids by Sebastian Lague, linked under Watch & read. The video covers the three rules of a boid and then obstacle avoidance; here you build the rules, the update step and the wrapping world in NumPy, and check them against a brute-force search.

Everything a boid does depends on its neighbors: the other boids closer than a fixed radius, never including itself. Each of three rules turns that set into a steering vector.

  • Separation pushes away from each neighbor, harder when it is close. Summing offset / |offset|² over the neighbors, with the offset pointing away, weights each one by 1 / distance.
  • Alignment is the mean neighbor velocity minus your own velocity. It is zero when you already move with the crowd.
  • Cohesion is the mean offset to the neighbors, a vector that points at their centroid.

A boid with no neighbors gets zero from all three and coasts. Here is one boid at the origin moving along x with two neighbors, one at (0.1, 0) moving up and one at (0, 0.2) moving down.

Python
import numpy as np

me, v_me = np.array([0.0, 0.0]), np.array([1.0, 0.0])
nb = np.array([[0.1, 0.0], [0.0, 0.2]])
v_nb = np.array([[0.0, 1.0], [0.0, -1.0]])
off = nb - me
print((-off / (off * off).sum(axis=1, keepdims=True)).sum(axis=0).round(6).tolist())
print((v_nb.mean(axis=0) - v_me).round(6).tolist())
print(off.mean(axis=0).round(6).tolist())

The three lines are separation (-10, -5), alignment (-1, 0) and cohesion (0.05, 0.1). The near neighbor at distance 0.1 dominates separation, which is the point of the 1 / distance weight. With weights 1.5, 1 and 1 the steering is (-15.95, -7.4), length 17.58. A force limit of 2 shortens it to (-1.814, -0.842), the same direction at a tenth of the length. Without limit, one close pair would fling boids across the world.

One time step, read from the old state
start / 6
Every boid runs the top row against the same old pos and vel. Only after all of them have a new velocity do speeds get clamped and positions move.
One time step, read from the old state
Every boid runs the top row against the same old pos and vel. Only after all of them have a new velocity do speeds get clamped and positions move.

The world is a torus: leave on the right, return on the left. Distances must respect that. On a unit torus a boid at x = 0.9 and one at x = 0.1 are 0.2 apart, with the second one ahead. The shortest displacement from a to b is (b - a + L/2) mod L - L/2 per axis, where L is the side. Using plain subtraction gives -0.8, so boids near an edge ignore neighbors on the other side and the flock splits along the seam.

Python
import numpy as np

def wrap_delta(a, b, size):
    return (b - a + size / 2) % size - size / 2

print(round(float(wrap_delta(0.9, 0.1, 1.0)), 6), round(float(wrap_delta(0.1, 0.9, 1.0)), 6))
print(round(0.1 - 0.9, 6))

The most common structural mistake is updating in place. If boid 3 writes its new velocity into the array before boid 4 is processed, boid 4 reacts to a state that never existed, and the result depends on the order of the rows. Take three boids that each move to the mean of the other two velocities.

Python
import numpy as np

v = np.array([0.0, 1.0, 2.0])
simultaneous = np.array([(v.sum() - x) / 2 for x in v])
w = v.copy()
for i in range(3):
    w[i] = (w.sum() - w[i]) / 2
print(simultaneous.tolist())
print(w.round(4).tolist())

Reading the old state gives (1.5, 1, 0.5), mirror-symmetric as the inputs are. The in-place loop gives (1.5, 1.75, 1.625): the last boid is treated differently only because of where it sits in the array. Allocate a new velocity array, fill it from the old arguments, and return it. The second mistake is forgetting that a boid is at distance zero from itself. If it counts as its own neighbor, separation divides by zero and the other two rules drift toward the boid's own values.

Two smaller details. Alignment and cohesion are differences, so a boid in the middle of a still crowd feels nothing. And a velocity of exactly zero has no direction, so speed clamping leaves it at zero rather than inventing one.

You cannot compare a flock with a reference output, so the tests ask other questions. A loop over the nine periodic images of every boid finds the nearest copy a different way from the modular formula. Relabeling the boids must relabel the result. A mirrored pair must keep a total velocity of zero. Shifting the whole swarm must shift the outcome. With 40 boids at random headings, the polarization (the length of the mean unit heading, 1 when all agree) rises from 0.259 to 0.996 in 150 steps.

Alignment emerging from local rules
Polarization of 40 boids over 150 steps (radius 0.2, dt 0.05, seed 3). Headings start random at 0.259 and line up.
Alignment emerging from local rules
Polarization of 40 boids over 150 steps (radius 0.2, dt 0.05, seed 3). Headings start random at 0.259 and line up.

Passing those tests means the code does what this page says. It does not mean the flock looks alive: the weights, the radius and the limits decide that, and the checks cannot judge it. It also does not cover obstacles or three dimensions.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

The video this lesson is paired with: the three rules of a boid, then obstacle avoidance and speeding the simulation up. Watch it first, then build the rules and the update step here and test them against a brute-force oracle.