Step 12

Let's implement a kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area.

Collision detection is a very common task for game development. We will likely need this between other objects in the game. So, let's implement it at a higher level of abstraction. Add the following method to the Block.js.

// assume other has {x, y, width, height}
intersects(other) {
  let tw = this.width;
  let th = this.height;
  let rw = other.width;
  let rh = other.height;
  if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
    return false;
  }
  let tx = this.x;
  let ty = this.y;
  let rx = other.x;
  let ry = other.y;
  rw += rx;
  rh += ry;
  tw += tx;
  th += ty;
  //      overflow || intersect
  return (
    (rw < rx || rw > tx) &&
    (rh < ry || rh > ty) &&
    (tw < tx || tw > rx) &&
    (th < ty || th > ry)
  );
}

The method above detects if two rectangles intersect. This is a common strategy to collision detection (there are other strategies, see e.g. Collision Detection in Javascript or Collision Detection and Physics).

Now add the following method to Ball.js

colides(paddle) {
  if (this.intersects(paddle)) {
    this.dy *= -1; // switch direction
  }
}

Finally, update the script.js file by adding this line to the draw method:

ball.colides(paddle);

Save your code again and try it in your browser. You may not notice the ball is bouncing off the paddle as it also bounces off the bottom edge of the canvas. We are going to change that behavior in the next step though.