setup()
setup() runs once when the sketch first loads. It's the right place to size the canvas and give your objects their starting position and velocity before the animation loop begins.
🔬 This sets the ball's starting speed randomly between -5 and 5 in each direction. What happens visually if you widen the range to random(-15, 15)? What if you narrow it to random(-1, 1)?
ballVX = random(-5, 5);
ballVY = random(-5, 5);
function setup() {
// Create a canvas that fills the entire window
createCanvas(windowWidth, windowHeight);
// Initialize the ball's position to the center of the canvas
ballX = width / 2;
ballY = height / 2;
// Initialize the ball's velocity with random values
// The ball will move with a speed between -5 and 5 pixels per frame
ballVX = random(-5, 5);
ballVY = random(-5, 5);
// Ensure the ball doesn't start stationary
if (ballVX === 0 && ballVY === 0) {
ballVX = 3;
ballVY = 3;
}
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
if (ballVX === 0 && ballVY === 0) {
Guards against the rare case where random() returns exactly 0 for both velocities, which would leave the ball frozen forever
createCanvas(windowWidth, windowHeight);- Creates a drawing canvas that exactly matches the browser window's current width and height, making the sketch full-screen
ballX = width / 2;- Places the ball's starting horizontal position exactly in the middle of the canvas
ballY = height / 2;- Places the ball's starting vertical position exactly in the middle of the canvas
ballVX = random(-5, 5);- Picks a random horizontal speed between -5 and 5, so the ball starts moving in an unpredictable direction and pace
ballVY = random(-5, 5);- Picks a random vertical speed between -5 and 5, similarly randomizing vertical motion
if (ballVX === 0 && ballVY === 0) {- Checks the very unlikely case that both random values happened to be exactly zero
ballVX = 3;- Gives the ball a fallback horizontal speed so it never stays perfectly still
ballVY = 3;- Gives the ball a fallback vertical speed for the same reason