Three.js Boids Flocking Simulation (Separation, Alignment, Cohesion)

Reynolds boids in Three.js, with thousands of instanced birds steering by separation, alignment and cohesion using a spatial hash, avoiding obstacles and scattering from a hunting predator.

Key topics: boids, flocking simulation, three.js boids, swarm behavior, reynolds steering, emergent behavior

What this code does

- Three Rules: separation steers away from close neighbours (weighted 1/d²), alignment matches their average heading, cohesion moves toward their centre.
- Locality: each boid sees only neighbours within the perception radius, and global flocking emerges from these local rules.
- Spatial Hash: boids are bucketed into radius-sized cells, so a neighbour search checks 27 cells instead of every boid, O(n) rather than O(n²).
- Predator & Obstacles: a strong repulsion field causes the classic split-and-rejoin "flash expansion" around the chaser.
- Speed Limits: velocity is clamped between minimum and maximum speeds, so boids never stall or explode.
- Controls: boid count, the three rule weights, perception radius, max speed, predator and obstacles.

Continue Learning

JavaScript Implementation

ES6+
// Reynolds' boids: three local steering rules from neighbours within radius r
for (const b of boids) {
  const near = neighbours(b, r) // use a spatial grid for thousands of boids
  if (!near.length) continue
  const align = average(near.map(n => n.vel)).sub(b.vel)         // match heading
  const cohere = average(near.map(n => n.pos)).sub(b.pos)        // move toward the centre
  const separate = near.reduce((s, n) => s.add(b.pos.clone().sub(n.pos).divideScalar(b.pos.distanceToSquared(n.pos))), new THREE.Vector3())
  b.vel.addScaledVector(align, 0.6 * dt).addScaledVector(cohere, 0.4 * dt).addScaledVector(separate, 2 * dt).clampLength(3, 9)
}
boids.forEach(b => b.pos.addScaledVector(b.vel, dt))