setup()
setup() runs once when the sketch starts. It's the place to initialize your canvas, create initial objects, and attach event listeners. The windowResized() function at the bottom ensures the canvas stays full-window as the user resizes their browser or rotates their device.
function setup() {
createCanvas(windowWidth, windowHeight);
// Create our initial set of eaters
for (let i = 0; i < EATER_COUNT; i++) {
eaters.push(new Eater());
}
// --- Create and Position the Spawn Button ---
// Select the button by its ID from index.html
// See: https://p5js.org/reference/p5/select/
spawnButton = select('#spawnButton');
// Attach a touchStarted event listener to the button
// This works well for both mouse clicks and touch taps
// See: https://p5js.org/reference/p5/Element/touchStarted/
spawnButton.touchStarted(spawnNewEater);
}
Line-by-line explanation (5 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-window canvas that will resize responsively
for (let i = 0; i < EATER_COUNT; i++) {
eaters.push(new Eater());
}
Spawns the initial eaters and adds them to the global array
spawnButton = select('#spawnButton');
Grabs the HTML button element by its ID so we can attach event listeners to it
spawnButton.touchStarted(spawnNewEater);
Wires the button so that tapping it calls spawnNewEater()
createCanvas(windowWidth, windowHeight);- Creates a p5.js canvas that fills the entire window. windowWidth and windowHeight are p5.js global variables that update when the window resizes.
for (let i = 0; i < EATER_COUNT; i++) {- Loops EATER_COUNT times (5 by default) to create the initial population of eaters.
eaters.push(new Eater());- Creates a new Eater object and adds it to the eaters array. The Eater constructor automatically picks a random starting position on the canvas.
spawnButton = select('#spawnButton');- Uses p5.js's select() function to find the HTML element with id='spawnButton' and stores a reference to it so we can listen for clicks/taps.
spawnButton.touchStarted(spawnNewEater);- Attaches a touchStarted event listener to the button element. When the user taps or clicks the button, the spawnNewEater function will be called automatically.