setup()
setup() runs once when the sketch starts. It initializes all variables, configures the canvas size, and prepares text settings. Think of it as the game's startup phase.
function setup() {
createCanvas(windowWidth, windowHeight);
// Set initial player position to the center of the canvas
playerX = width / 2;
playerY = height / 2;
// Place the first item at a random position
placeNewItem();
// Set text properties for score display
textSize(32);
textAlign(LEFT, TOP);
}
Line-by-line explanation (6 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a canvas that fills the entire browser window
playerX = width / 2;
playerY = height / 2;
Places the player circle in the center of the canvas at game start
textSize(32);
textAlign(LEFT, TOP);
Sets score text to be large and positioned from the top-left
createCanvas(windowWidth, windowHeight);- Creates a canvas that dynamically sizes to your entire browser window, so the game fills the screen
playerX = width / 2;- Sets the player's starting X position to the horizontal center of the canvas
playerY = height / 2;- Sets the player's starting Y position to the vertical center of the canvas
placeNewItem();- Calls the helper function to spawn the first item at a random location
textSize(32);- Makes the score text 32 pixels tall so it is easy to read
textAlign(LEFT, TOP);- Aligns text from its top-left corner instead of center, positioning it neatly at coordinate (10, 10)