setup()
setup() runs once before the game starts. Here it's used not just to create the canvas, but to compute several 'derived' constants (figureGroundY and the vehicle Y positions) that depend on the canvas height, which isn't known until createCanvas() has run.
function setup() {
createCanvas(windowWidth, windowHeight);
textSize(32);
textAlign(CENTER, CENTER);
rectMode(CENTER); // Draw rectangles from their center
ellipseMode(CENTER); // Draw ellipses from their center
// Initialize catcher
catcher = {
x: width / 2,
y: height - catcherHeight / 2 - 20, // Catcher remains relative to the bottom
width: catcherWidth,
height: catcherHeight
};
// Define figureGroundY here, after height is available
figureGroundY = height - 50; // New consistent ground level for figures and ground vehicles
// Adjust vehicle Y positions relative to figureGroundY
policeCarY = figureGroundY - policeCarHeight / 2 - 10; // Car is slightly above ground
fireTruckY = figureGroundY - fireTruckHeight / 2 - 10;
towTruckY = figureGroundY - towTruckHeight / 2 - 10;
}
Line-by-line explanation (6 lines)
createCanvas(windowWidth, windowHeight);- Makes the canvas fill the entire browser window.
rectMode(CENTER); // Draw rectangles from their center- Changes rect() so its x,y arguments refer to the center of the rectangle instead of the top-left corner - this makes positioning figures and vehicles much easier.
ellipseMode(CENTER); // Draw ellipses from their center- Same idea but for ellipse()/circle() - keeps all shapes centered on the same point.
catcher = { x: width / 2, y: height - catcherHeight / 2 - 20, // Catcher remains relative to the bottom width: catcherWidth, height: catcherHeight };- Creates the catcher as a plain JavaScript object holding its position and size, centered horizontally and near the bottom of the screen.
figureGroundY = height - 50; // New consistent ground level for figures and ground vehicles- Defines one shared 'ground line' Y coordinate that every walking figure and every ground vehicle will be drawn at, so everything lines up visually.
policeCarY = figureGroundY - policeCarHeight / 2 - 10; // Car is slightly above ground- Calculates the police car's fixed vertical position relative to the shared ground level rather than a hardcoded number.