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

Hit the ball

A paddle that does nothing is just decoration. Let’s bounce the ball off it and count your hits. First, add a score variable at the top:

let hits = 0;

Now the hit itself. In update(), right after the wall-bounce block, add:

if (bx < 10 && by > paddleY && by < paddleY + PH && bdx < 0) {
  bdx = -bdx;        // send it back toward the wall
  hits = hits + 1;   // one more hit!
}
💡

That check is one true/false answer built from four comparisons joined with && (all must be true): the ball is near the paddle and below its top and above its bottom and moving left toward it. The last part stops it getting stuck buzzing against the paddle. That’s Booleans and If statements doing real work.

Show the score. At the top of draw(), just after cls(0), add:

print('Hits: ' + hits, 4, 4, 7);

Your whole program now — save and see how long a rally you can keep going:

let paddleY = 54;
const PH = 20;

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

let hits = 0;

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;
  }
  if (bx < 10 && by > paddleY && by < paddleY + PH && bdx < 0) {
    bdx = -bdx;
    hits = hits + 1;
  }
}

function draw() {
  cls(0);
  rectfill(124, 0, 127, 127, 6);
  print('Hits: ' + hits, 4, 4, 7);
  rectfill(6, paddleY, 8, paddleY + PH, 7);
  circfill(bx, by, 2, 7);
}