← All lessons/Capstone Projects· Lesson 30 of 32

Bouncing ball

Combine variables, the draw loop, and conditionals to animate a ball that bounces off every edge of the canvas.

About 12 min

Your first real animation

Time to combine three things you've already learned into one moving sketch: variables to remember where the ball is and how fast it travels, the `draw()` loop to redraw it ~60 times a second, and conditionals to make it turn around at the walls.

The big idea behind almost every animation is this: keep a value in a variable, change it a little every frame, and draw using that value. A ball that moves right is just x = x + speed repeated over and over.

Remembering position

We declare the ball's position outside draw() so the value survives between frames. If we declared it inside, it would reset to the start every single frame and the ball would never go anywhere.

let x = 200;
let speed = 4;

function draw() {
  background(220);
  x = x + speed; // move a little each frame
  ellipse(x, 200, 40, 40);
}
Declare state at the top; change it inside draw().

Bouncing with a conditional

Left alone, the ball sails off the right edge forever. To bounce, we check its position with an if: when it reaches an edge, we flip the direction by negating the speed. speed = -speed turns 4 into -4 (now moving left) and -4 back into 4.

A ball that bounces left and right. Watch it ping-pong!

Why negate the speed?

Flipping the sign is the whole trick. A positive speed moves right (or down); a negative one moves the opposite way. speed = -speed reverses the direction without you tracking which way it was going.

Now you'll do the full version: a ball that bounces off all four walls. That means tracking both an x and a y, giving each its own speed, and checking each against its edges.

Your turn

Build a ball that bounces around the whole canvas. Declare x, y, xspeed, and yspeed variables, then in draw() clear the background, move the ball, use `if` statements to flip xspeed at the left/right edges and yspeed at the top/bottom edges, and draw the ball with `ellipse`.

  • Declare x, y, xspeed, and yspeed above draw() so they remember their values.
  • Inside draw(), call background(...) first to wipe the previous frame.
  • Add each speed to its position: x = x + xspeed; and y = y + yspeed;.
  • Use an if to bounce: when x passes the left/right edge, xspeed = -xspeed; same idea for y.
  • Finish by drawing the ball with ellipse(x, y, 40, 40);.
Hints