setup()
setup() runs once at the very beginning. It is where you define the canvas size and initialize all your game objects with their starting properties. Using objects (like ball = { ... }) keeps related data organized instead of scattering variables everywhere.
function setup() {
createCanvas(600, 400);
ball = {
x: width / 2,
y: height / 2,
r: 10,
xspeed: 4,
yspeed: 3
};
leftPaddle = {
x: 20,
y: height / 2 - 40,
w: 10,
h: 80
};
rightPaddle = {
x: width - 30,
y: height / 2 - 40,
w: 10,
h: 80
};
}
Line-by-line explanation (12 lines)
🔧 Subcomponents:
createCanvas(600, 400);
Creates the 600x400 pixel game board where all action happens
ball = {
x: width / 2,
y: height / 2,
r: 10,
xspeed: 4,
yspeed: 3
};
Creates an object storing the ball's position (x, y), radius (r), and velocity (xspeed, yspeed)
leftPaddle = {
x: 20,
y: height / 2 - 40,
w: 10,
h: 80
};
rightPaddle = {
x: width - 30,
y: height / 2 - 40,
w: 10,
h: 80
};
Creates two paddle objects with position (x, y), width (w), and height (h)
createCanvas(600, 400);- Creates a 600 pixel wide by 400 pixel tall canvas—the playing field for Pong
ball = {- Starts defining the ball as an object that will store all its properties
x: width / 2,- Sets the ball's starting x position to the exact center of the canvas (300 pixels)
y: height / 2,- Sets the ball's starting y position to the exact center vertically (200 pixels)
r: 10,- Stores the ball's radius as 10 pixels, so its diameter when drawn will be 20 pixels
xspeed: 4,- The ball will move 4 pixels to the right each frame (or left when bouncing)
yspeed: 3- The ball will move 3 pixels down each frame (or up when bouncing off top/bottom)
leftPaddle = {- Creates an object to store all the left paddle's properties in one place
x: 20,- Positions the left paddle 20 pixels from the left edge of the canvas
y: height / 2 - 40,- Positions the left paddle vertically centered (height / 2) then nudges it up 40 pixels so it's centered on its middle
w: 10,- The paddle is 10 pixels wide, making it a thin vertical rectangle
h: 80- The paddle is 80 pixels tall, giving it a reasonable target size for hitting the ball