Step 14
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 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
class.
// 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 the Ball
class:
colides(paddle) {
if (this.intersects(paddle)) {
this.dy *= -1; // switch direction
}
}
Finally, add the following statement to the draw
function in the main.js
file:
ball.colides(paddle);
Save your code and observer the changes in the browser.