Kamel Ghabte · Course · Free

Boids & Flocking

Simulate a school of fish with Reynolds' algorithm in p5.js.

The concept

The flocking algorithm (Reynolds, 1987) simulates collective behavior with 3 rules: separation (avoid close neighbors), alignment (match their heading), cohesion (move toward group center). Each agent only sees locally, but global behavior is realistic.

The code

// Boids: 50 agents with separation/alignment/cohesion
let boids = [];
function setup() {
  createCanvas(400, 280);
  for (let i = 0; i < 50; i++) boids.push({x:random(width),y:random(height),vx:random(-1,1),vy:random(-1,1)});
}
function draw() {
  background(11,15,20);
  for (let b of boids) {
    // Simplified: steer toward center + avoid close
    let cx=0,cy=0,n=0;
    for (let o of boids) { if(o!==b&&dist(b.x,b.y,o.x,o.y)<50){cx+=o.x;cy+=o.y;n++;}}
    if(n){b.vx+=(cx/n-b.x)*0.003;b.vy+=(cy/n-b.y)*0.003;}
    b.x+=b.vx;b.y+=b.vy; b.x=(b.x+width)%width;b.y=(b.y+height)%height;
    fill(55,227,195);noStroke();ellipse(b.x,b.y,5,5);
  }
}

Going further

Explore other free courses on the Learn page, or book a call to discuss your project.

Want to go further?

Book a discovery call →