setup()
setup() runs once when the sketch starts. It initializes all variables and prepares the canvas. The random velocity ensures the ball moves in a different direction each time you refresh the page. The stationary check is important because random(-5, 5) could theoretically return 0 for both velocities.
function setup() {
createCanvas(windowWidth, windowHeight);
ballX = width / 2;
ballY = height / 2;
ballVX = random(-5, 5);
ballVY = random(-5, 5);
if (ballVX === 0 && ballVY === 0) {
ballVX = 3;
ballVY = 3;
}
}
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight)
Creates a canvas that fills the entire browser window
ballX = width / 2; ballY = height / 2;
Places the ball at the center of the canvas
ballVX = random(-5, 5); ballVY = random(-5, 5);
Gives the ball a random starting direction and speed between -5 and 5 pixels per frame
if (ballVX === 0 && ballVY === 0) { ballVX = 3; ballVY = 3; }
Ensures the ball always moves by setting a default velocity if both random values happen to be 0
Line by Line:
createCanvas(windowWidth, windowHeight)- Creates a canvas that matches the full width and height of the browser window, making the sketch responsive
ballX = width / 2- Sets the ball's starting horizontal position to the center of the canvas
ballY = height / 2- Sets the ball's starting vertical position to the center of the canvas
ballVX = random(-5, 5)- Assigns a random horizontal velocity between -5 and 5 pixels per frame, giving the ball a random starting direction
ballVY = random(-5, 5)- Assigns a random vertical velocity between -5 and 5 pixels per frame
if (ballVX === 0 && ballVY === 0)- Checks if both velocity values are exactly 0 (a rare but possible outcome from random())
ballVX = 3; ballVY = 3;- If the ball would be stationary, sets default velocities of 3 pixels per frame in both directions