setup()
setup() runs once when the sketch starts. It's the ideal place to build expensive one-time resources - like the sky gradient buffer here - and to populate arrays of objects before the animation loop begins.
function setup() {
createCanvas(windowWidth, windowHeight);
// Create sky gradient once
skyGraphic = createGraphics(windowWidth, windowHeight);
drawSkyGradient(skyGraphic);
// Initialize flock
for (let i = 0; i < NUM_BOIDS; i++) {
boids.push(new Boid());
}
// Smoother visuals
frameRate(60);
}
Line-by-line explanation (6 lines)
🔧 Subcomponents:
for (let i = 0; i < NUM_BOIDS; i++) {
boids.push(new Boid());
}
Creates NUM_BOIDS new Boid objects, each with its own random position and velocity, and stores them all in the boids array.
createCanvas(windowWidth, windowHeight);- Makes the canvas fill the entire browser window so the flock has the full screen to fly around in.
skyGraphic = createGraphics(windowWidth, windowHeight);- Creates a separate, offscreen drawing buffer the same size as the canvas - this lets the sky be drawn once and reused every frame instead of redrawn from scratch.
drawSkyGradient(skyGraphic);- Calls the helper function to paint the blue gradient into that offscreen buffer a single time.
for (let i = 0; i < NUM_BOIDS; i++) {- Loops NUM_BOIDS times (100 by default) to build the initial flock.
boids.push(new Boid());- Creates a brand-new Boid object (with its own random position and velocity from the constructor) and adds it to the boids array.
frameRate(60);- Asks p5.js to try to run draw() 60 times per second for smooth, consistent animation.