setup()
setup() runs once when the sketch starts. It's the perfect place to create your canvas, pre-generate static visual elements (like these stars), and call initialization functions. Notice how the stars are pre-generated here once, not every frame in draw()—this is a performance pattern worth remembering.
function setup() {
createCanvas(800, 600);
textAlign(CENTER, CENTER);
// Generate static stars once
for (let i = 0; i < 80; i++) {
stars.push({ x: random(width), y: random(height * 0.6), r: random(1, 3) });
}
resetGame();
}
Line-by-line explanation (5 lines)
🔧 Subcomponents:
for (let i = 0; i < 80; i++) {
stars.push({ x: random(width), y: random(height * 0.6), r: random(1, 3) });
}
Creates 80 randomly positioned stars that stay fixed in the night sky backdrop
createCanvas(800, 600);- Creates a landscape-oriented 800×600 pixel canvas—wide enough for side-scrolling gameplay
textAlign(CENTER, CENTER);- Sets all text to draw centered horizontally and vertically, making UI text positioning easier
for (let i = 0; i < 80; i++) {- Loop runs 80 times to create an array of stars
stars.push({ x: random(width), y: random(height * 0.6), r: random(1, 3) });- Adds a star object with random x position (anywhere on canvas), y position (in upper 60% of screen), and radius (1-3 pixels). These stars are created once and never move.
resetGame();- Calls the resetGame() function to initialize all game variables to their starting values