setup()
setup() runs once when the sketch loads. It is the perfect place to initialize the canvas size and create the data structures (objects, arrays) that your game will use throughout its lifetime.
function setup() {
createCanvas(windowWidth, windowHeight);
player = {
x: width / 2,
y: height - 80,
w: 50,
h: 30,
speed: 7
};
resetGame(false); // set initial values but stay on start screen
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
player = {
x: width / 2,
y: height - 80,
w: 50,
h: 30,
speed: 7
};
Creates the player ship as a plain JavaScript object with position (x, y), dimensions (w, h), and movement speed
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window, making the game responsive to window size
player = {- Begins declaring the player as an object (not a class) with several properties that define its state
x: width / 2,- Sets the player's horizontal starting position to the center of the canvas
y: height - 80,- Sets the player's vertical position 80 pixels from the bottom, giving a border area
w: 50,- Defines the player ship's width as 50 pixels—this is used in collision detection and drawing
h: 30,- Defines the player ship's height as 30 pixels
speed: 7- Sets how many pixels the player moves left or right per frame when a key is held down
resetGame(false);- Calls resetGame() with false to initialize game variables but keep the game in 'start' state rather than immediately playing