setup()
setup() runs once when the sketch loads. It is where you initialize your canvas, variables, and any objects you need before the game starts. The player object uses curly braces to bundle related data together—this pattern is called an object literal and is fundamental to organizing game code.
function setup() {
createCanvas(windowWidth, windowHeight);
// Tip: Use windowWidth/windowHeight for responsive canvas
// Initialize player at the bottom center
player = {
x: width / 2,
y: height - 50,
size: 40,
speed: 8
};
// Create an initial set of points
for (let i = 0; i < 10; i++) {
createPoint();
}
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
player = {
x: width / 2,
y: height - 50,
size: 40,
speed: 8
};
Creates a player object with position, size, and movement speed properties
for (let i = 0; i < 10; i++) {
createPoint();
}
Populates the game with 10 falling objects at the start
createCanvas(windowWidth, windowHeight);- Creates a full-screen canvas that responds to window size—windowWidth and windowHeight are p5.js variables that update when the window resizes
player = {- Starts defining the player as a JavaScript object that will hold all its properties in one place
x: width / 2,- Sets the player's horizontal position to the horizontal center of the canvas
y: height - 50,- Places the player near the bottom of the canvas, 50 pixels up from the bottom edge
size: 40,- The player circle will have a diameter of 40 pixels
speed: 8- The player moves 8 pixels per frame when arrow keys are held down
for (let i = 0; i < 10; i++) {- Loops 10 times to create an initial batch of falling points
createPoint();- Calls the createPoint() helper function, which adds one random point to the points array