setup()
setup() runs exactly once when the sketch starts. It is the best place to initialize the canvas, set initial variable values, and configure text/color/stroke properties that stay constant throughout the game.
function setup() {
createCanvas(windowWidth, windowHeight); // Create a full-window canvas
gameStartTime = millis(); // Record the game start time
lastBugSpawnTime = millis(); // Record the last bug spawn time
textSize(24); // Set text size for UI
textAlign(LEFT, TOP); // Align text to the top-left
}
Line-by-line explanation (5 lines)
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window; windowWidth and windowHeight are built-in p5.js variables
gameStartTime = millis();- Stores the current time in milliseconds since the sketch started; used later to calculate elapsed time
lastBugSpawnTime = millis();- Records when the last bug was spawned; used in draw() to check if enough time has passed for the next spawn
textSize(24);- Sets the font size for all text drawn after this line to 24 pixels
textAlign(LEFT, TOP);- Anchors text so that the x,y coordinates you provide are the top-left corner of the text, not the center