Public
Edited
May 5, 2023
2 stars
Insert cell
Insert cell
myBoids = {
// Create a new simulation
const myBoids = new Boids();
// Add 200 boids
for (let i = 0; i < 100; i++){
myBoids.add();
}
return myBoids;
}
Insert cell
// See what happens when you change these
myBoids.alignment(1).cohesion(1).separation(1).perception(20).maxSpeed(4);
Insert cell
{
// Create a new context with the boids' dimensions
const ctx = DOM.context2d(myBoids.width(), myBoids.height());
// This is basically the Observable way of doing requestAnimationFrame
while(true) {
// Advance the boids one tick
myBoids.tick();
// Clear the context on each tick
ctx.clearRect(0, 0, myBoids.width(), myBoids.height());
// Loop through the "flock"
myBoids.each(boid => {
// Draw a circle at each boid's position
ctx.beginPath();
ctx.arc(...boid.pos, 5, Math.PI * 2, 0);
ctx.fill();
});
// You have to yield the canvas on each tick
yield ctx.canvas;
}
}
Insert cell
import { Boids } from "@harrystevens/vanilla-boids"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more