Algorithms

Boids: three rules of a flock

A flock turns, separates around an obstacle and gathers again. Each bird reacts to nearby birds. Try the three rules individually, then inspect one bird to see how its next direction is calculated.

Applied: 96 birds · seed 93717 · Three islands · active rules: 3/3.

Opposite edges are connected. Apply captures settings; restart and shared links reproduce them. This run: 600 ticks, up to 128 birds.

Video walkthrough

1000 birds and predators

A continuous 1:44 simulation with music and no narration. The flock flies through a narrow passage, predators hunt together, and a larger predator has to fly around the obstacle.

A flock without a leader

Craig Reynolds’s Boids model describes group motion through local interactions. A bird does not choose a route for the whole flock. Its position and velocity change in response to the birds around it.

The demo is a two-dimensional educational variant. Its circular perception has no viewing angle, and opposite edges of the field are connected. It illustrates how coordinated motion can emerge; it does not guarantee that all birds form one group or share one heading.

The three rules

Separation: steer away from birds that are too close. This example uses distances strictly below 26 units. A nearer neighbor contributes more strongly through its displacement divided by squared distance. Coincident birds use their IDs to choose opposite separation directions.

Alignment: take the average velocity of neighbors as the desired heading. Cohesion: steer toward their average relative position. Both use all other birds strictly within 90 units. Across a connected edge, the shortest wrapped displacement defines distance and direction.

Each nonzero desired direction is scaled to 2.3 units/tick; subtract the bird’s current velocity, then cap that steering vector at 0.045. The three weights are 1.9, 1 and 0.65. Turning off a rule sets its contribution to zero; it does not change which neighbors are shown.

Follow one bird’s decision

Enable Inspect one bird and choose its number. Playback pauses, the camera follows that bird, and the scene highlights its neighbors. The smaller ring marks close neighbors. Step forward to see the calculated direction become the bird’s actual next velocity.

The table shows weighted steering vectors, separate obstacle avoidance and their sum Δv. Add Δv to the current velocity, then limit its length to 1.2–2.8 units/tick. Contact with an obstacle may additionally correct position and reflect inward velocity. The next position uses this update and wraps at the field edges.

For a concrete calculation, put two birds at (100, 100) and (110, 100), both moving at (2, 0), with no obstacles. The first bird receives separation (−0.0855, 0), alignment (0.045, 0) and cohesion (0.02925, 0). Their sum is (−0.01125, 0), so its next velocity is (1.98875, 0).

Colored force arrows share a scale of ×700. The dashed sum is still a change in velocity; the text-colored dashed heading has a fixed drawing length. Compare the numeric velocities to compare speed. Inspection shows exact snapshots without interpolation and predicts the next tick, including beyond the final recorded tick.

Try different obstacles

Choose open space, one circle, three islands, a rounded wall or a narrow passage. Apply and restart captures the settings and rebuilds the run from the same seed. You can compare one change at a time by keeping the seed fixed.

Obstacle avoidance is an additional steering vector. It considers the current position and a point 12 velocity vectors ahead; nearby boundaries contribute outward and sideways steering. A separate contact response keeps bird centers at least 3 units from an obstacle’s surface. Circles and thick rounded segments define the geometry.

The passage is an experiment in local reactions, not a pathfinding problem. Birds have no global destination and may go around a wall or cross the connected edge. Avoidance does not guarantee that every bird passes through the opening. Separation between birds is steering rather than a hard collision constraint.

Four experiments

Disable alignment and watch how neighboring headings change. Disable cohesion to remove the tendency to return toward nearby birds. Disable separation to see how tightly groups can gather. These switches change tendencies rather than promise one specific final pattern.

For a baseline, choose open space and disable all three rules: initialized birds keep their velocities and travel straight across connected edges. Then restore one rule at a time. Seed and bird count define the starting flock; playback speed changes only presentation timing, so it does not change simulated trajectories.

One snapshot for every decision

Every bird reads the same old snapshot. Only after its decision is calculated does it receive a new position and velocity in a separate array. This prevents a later bird from reacting to an already moved neighbor in the same tick. The old state remains unchanged and can be revisited.

The site stores 600 updates plus the initial state, with up to 128 birds. At 1×, each tick occupies 50 ms; a final hold follows. The limit is chosen for this retained history, not inherited from the library’s generator example. A shared link saves applied settings, selected bird, inspection, position and playback speed; it opens paused.

What the simulation costs

For n birds and k obstacle pieces, a tick takes O(n² + nk): every bird scans all other birds and checks the small fixed set of obstacles. There are n(n−1) ordered neighbor checks per tick. Spatial indexing could reduce typical neighbor-search work, but is not used in this example.

Working state and a single snapshot require O(n + k) space. Retaining T ticks uses O(Tn + k), because obstacle geometry and configuration are shared. Scene projection, sorting drawable objects and rendering add their own work; these costs are separate from the movement rules.

Code: the three rules in open space

The executable JavaScript below matches the open-space variant, including wrapping, weights, force limits and synchronous updates. Obstacles and their contact response are described separately above. Inputs are an array of birds with stable unique IDs and valid positions and velocities.

Show the executable model
// Free space: the same three rules, without obstacles.
// Positions and velocities use world units per simulation tick.
function flockStep(birds, rules = {
  separation: true, alignment: true, cohesion: true
}) {
  const delta = (d, size) =>
    d > size / 2 ? d - size : d < -size / 2 ? d + size : d;
  const wrap = (x, size) => (x % size + size) % size;
  function steer(x, y, bird, weight) {
    const length = Math.hypot(x, y);
    if (length < 1e-9) return [0, 0];
    let dx = x / length * 2.3 - bird.vx;
    let dy = y / length * 2.3 - bird.vy;
    const force = Math.hypot(dx, dy);
    if (force > 0.045) { dx *= 0.045 / force; dy *= 0.045 / force; }
    return [dx * weight, dy * weight];
  }
  // map reads only the old birds array: updates are synchronous.
  return birds.map(bird => {
    let sx = 0, sy = 0, ax = 0, ay = 0, cx = 0, cy = 0;
    let neighbors = 0, close = 0;
    for (const other of birds) {
      if (other.id === bird.id) continue;
      const dx = delta(other.x - bird.x, 800);
      const dy = delta(other.y - bird.y, 500);
      const square = dx * dx + dy * dy;
      if (square >= 90 * 90) continue;
      neighbors++; ax += other.vx; ay += other.vy;
      cx += dx; cy += dy;
      if (square < 26 * 26) {
        close++;
        if (square > 1e-9) { sx -= dx / square; sy -= dy / square; }
        else sx += bird.id < other.id ? -1 : 1;
      }
    }
    const forces = [
      rules.separation && close ? steer(sx / close, sy / close, bird, 1.9) : [0, 0],
      rules.alignment && neighbors ? steer(ax / neighbors, ay / neighbors, bird, 1) : [0, 0],
      rules.cohesion && neighbors ? steer(cx / neighbors, cy / neighbors, bird, 0.65) : [0, 0]
    ];
    let vx = bird.vx, vy = bird.vy;
    for (const [x, y] of forces) { vx += x; vy += y; }
    const speed = Math.hypot(vx, vy);
    const limited = Math.max(1.2, Math.min(2.8, speed));
    if (speed < 1e-9) { vx = limited; vy = 0; }
    else { vx *= limited / speed; vy *= limited / speed; }
    return { ...bird, vx, vy,
      x: wrap(bird.x + vx, 800), y: wrap(bird.y + vy, 500) };
  });
}
const birds = [
  { id: 0, x: 100, y: 100, vx: 2, vy: 0 },
  { id: 1, x: 110, y: 100, vx: 2, vy: 0 }
];
const next = flockStep(birds); // next[0].vx = 1.98875

The same scene, different ways to explore

The movement model belongs to the application. AlgiViz supplies timeline sampling, stable object matching and scene dispatch; the application defines birds, perception rings and steering arrows. CanvasTake powers the shared Save video action. Use fullscreen for the moving scene, or share a paused calculation for someone else to inspect.

Craig Reynolds — BoidsAlgiVizCanvasTake