GameSpark/Tutorials Open editor ↗
Build Wall Ball · Step 3 of 6

The ball

Now the star of the show. A ball needs a position (bx, by) and a velocity — how fast it moves each frame (bdx, bdy). Add these four variables near the top, under const PH:

let bx = 64;
let by = 64;
let bdx = 1.5;
let bdy = 1;

Next, make it move and bounce. Inside update(), after the paddleY = mid(...) line, add:

bx += bdx;
by += bdy;
if (by < 2 || by > 125) {
  bdy = -bdy;   // bounce off top / bottom
}
if (bx > 122) {
  bdx = -bdx;   // bounce off the wall
}

Adding the velocity each frame is what makes it move; flipping a velocity (bdy = -bdy) turns a bounce. Finally, draw the ball — at the end of draw(), add:

circfill(bx, by, 2, 7);
💡

We bounce off the wall when bx > 122 (not 124) because the ball has a radius of 2 — its edge touches the wall a couple of pixels before its center reaches it. That’s the same edge-vs-center idea as Motion and bouncing.

Your whole program now — save and watch it ricochet (it still sails past your paddle; that’s next):

let paddleY = 54;
const PH = 20;

let bx = 64;
let by = 64;
let bdx = 1.5;
let bdy = 1;

function update() {
  if (key('ArrowUp')) {
    paddleY -= 2;
  }
  if (key('ArrowDown')) {
    paddleY += 2;
  }
  paddleY = mid(0, paddleY, 128 - PH);

  bx += bdx;
  by += bdy;
  if (by < 2 || by > 125) {
    bdy = -bdy;
  }
  if (bx > 122) {
    bdx = -bdx;
  }
}

function draw() {
  cls(0);
  rectfill(124, 0, 127, 127, 6);
  rectfill(6, paddleY, 8, paddleY + PH, 7);
  circfill(bx, by, 2, 7);
}