skip to content

In Reynolds' boids flocking, what do separation, alignment and cohesion each compute, and what decides which flockmates a boid reacts to?

level: middleimportance: should knowfreq 55%

answer

  1. three local rules, no leader
  2. too close, same heading, centre
  3. neighbour radius and view angle
  4. spatial grid sized to the radius

basics

~20 s

Separation steers away from flockmates that are too close, alignment toward their average heading, cohesion toward their average position. A boid reacts only to neighbours inside a radius, often within a view angle, so the flock emerges from local rules.

solid answer

~50 s

Each rule yields a steering force, and the weighted sum is truncated to the maximum force. **Separation** adds a push away from each close neighbour, weighted so that nearer ones push harder, for example by `1 / distance`. **Alignment** steers toward the neighbours' average velocity: `average(velocity) - velocity`. **Cohesion** seeks the neighbours' centroid. The **neighbourhood** is local: a radius, usually with a view angle that leaves a blind spot behind, and sometimes a fixed number of nearest neighbours, which keeps the flock coherent as density changes. Separation often gets a smaller radius and a weight that dominates at short range. Checking all pairs costs `O(n^2)` per tick; binning boids into a grid with cells as wide as the radius limits each query to 9 cells in 2D or 27 in 3D. Extra behaviours, such as orbiting a point and obstacle avoidance, sit beside the three rules.

code

pseudocode · 17 lines
pseudocode
function flock(boid, neighbours, wSep, wAli, wCoh):
    // neighbours are already filtered by radius and view angle
    if neighbours is empty:
        return (0, 0)
    separation = (0, 0); averageVelocity = (0, 0); centroid = (0, 0)
    for other in neighbours:
        offset = boid.position - other.position
        d = length(offset)
        if d > 0:
            separation = separation + offset / (d * d)   // unit offset scaled by 1 / d
        averageVelocity = averageVelocity + other.velocity
        centroid = centroid + other.position
    averageVelocity = averageVelocity / count(neighbours)
    centroid = centroid / count(neighbours)
    alignment = averageVelocity - boid.velocity
    cohesion = seek(boid, centroid)
    return truncate(wSep * separation + wAli * alignment + wCoh * cohesion, boid.maxForce)

go deeper

for a junior

Recall the three rules and what each averages or avoids, and that a boid only looks at neighbours inside a radius.

for a middle

Explain how the rule forces are weighted and truncated, why separation is distance-weighted, and how a uniform grid makes neighbour queries cheap.

for a senior

Diagnose clumping, scattering or fragmenting from the weights and radii, and add goal and avoidance behaviours without the flocking rules overriding them.

for a principal

Weigh how many agents the game truly needs to flock and at what cost per tick, and when a cheaper crowd or particle approach is the better tool.

## Three local rules Reynolds' boids model produces flocking without any boid knowing the flock's shape or following a leader. Each boid applies three rules to the flockmates near it: | Rule | Computes | Steering | |---|---|---| | **Separation** | offsets from neighbours that are too close | push away, harder for nearer neighbours | | **Alignment** | the neighbours' average velocity | steer toward that heading and speed | | **Cohesion** | the neighbours' average position | seek that centroid | Separation keeps birds from overlapping, alignment makes them fly the same way, and cohesion stops the group from drifting apart. The interesting behaviour, such as splitting around an obstacle and rejoining, emerges from the three rules interacting. ## The neighbourhood What counts as "near" shapes the result as much as the rules do: - **Radius.** Only boids within a distance contribute. Too small and the flock fragments; too large and every boid reacts to the whole flock, which looks rigid and costs more. - **View angle.** Ignoring boids in a blind spot behind gives a more natural, front-led response. - **Separate radii.** Separation usually uses a shorter radius than alignment and cohesion, so it only acts on genuine crowding. - **Fixed neighbour count.** Some implementations react to the nearest few boids rather than to everything within a radius. The flock then holds together better when density varies, because a sparse boid still has neighbours to follow. ## Combining the rules A typical update for one boid: 1. Collect the neighbours that pass the radius and view-angle tests. 2. Sum the separation pushes, each a unit offset scaled by `1 / distance` (some use `1 / distance^2`). 3. Average the neighbours' velocities and steer toward the average: `average - velocity`. 4. Average their positions and seek the centroid, as the seek behaviour would. 5. Weight and add the three forces, plus any goal or avoidance behaviours, and truncate to the maximum force. Separation's weight must win at short range, or the flock collapses into a jittering ball; cohesion that is too strong has the same effect. ## Steering a flock around a tower Pure boids wander as a group but go nowhere in particular. To have a flock of birds circle a tower: - Add a **goal behaviour**: each bird seeks a point that moves around the tower, or steers toward a tangent of the circle around it. - Add **obstacle avoidance** for the tower itself, and let it override the flocking rules when a collision is imminent rather than averaging with them. - Keep the goal weight modest, so the circling comes from a few birds' pull spreading through alignment and cohesion rather than every bird tracing the same circle. ## Making it scale Finding neighbours naively means testing every pair: `n * (n - 1) / 2` checks per tick, or `O(n^2)`. For a few dozen birds that is fine; for thousands it dominates the frame. The standard fix is a **uniform grid** or spatial hash with cells as wide as the largest neighbour radius: - Any neighbour within the radius lies in the boid's own cell or an adjacent one, so a query touches 3 x 3 = 9 cells in 2D or 3 x 3 x 3 = 27 in 3D. - Rebuilding the grid each tick is linear in the number of boids. - The cost becomes roughly the number of boids times the boids per neighbourhood, which degrades again only if the flock packs most birds into a few cells. - Read last tick's positions and velocities and write new ones to a second buffer. Updating in place makes each boid's result depend on the order the loop visits them, and the double buffer also lets the per-boid work spread across worker threads. ## Typical tuning failures - **Clumping:** separation too weak or its radius too small; birds overlap and jitter. - **Exploding:** separation too strong compared with cohesion; the flock scatters. - **Rigid marching:** alignment radius so large that every bird copies the same heading. - **Fragmenting:** neighbour radius too small for the flock's spacing, so groups lose contact and split for good. - **Oscillation:** a high force cap with strong opposing rules makes birds flick back and forth each tick. - **Edge effects** are expected rather than a bug: birds on the rim have neighbours on one side only, so cohesion pulls them inward, which helps give the flock a defined outline.

  • Why might you limit each boid to its nearest few neighbours instead of everyone inside a radius?
    With a radius, a boid in a sparse region may see nobody and drift off, while one in a dense clump reacts to dozens and costs more. A fixed count keeps the work per boid constant and gives every boid something to follow whatever the spacing, so the flock stays coherent as it stretches and compresses. Finding the nearest few still needs a spatial structure to stay cheap.
  • How would you add obstacle avoidance to a flock without the flock rules diluting it?
    Do not just add it to the weighted sum, where alignment and cohesion can outvote it. Give avoidance priority: when it reports an imminent collision, apply it first and let the flocking forces use only the leftover force budget, or skip them for that tick. The flock then bends around the obstacle and the flocking rules pull it back together afterwards.

  • Each boid steers toward the centre of the whole flock.
  • A flock needs a leader boid that all the others follow.
  • Alignment steers a boid toward the average position of its neighbours.
  • Separation pushes as hard on a distant neighbour as on one almost touching.
  • Testing every pair of boids each tick is fine for thousands of birds.