Time for action – hitting the ball with the paddles
We will use an approach, similar to that of checking the boundary, to check the collision:
- Open the
js/pingpong.js
file that we used in the previous section. - In the
moveBall
function, we have already reserved the place to put the collision detection code there. Find the line with//
check
paddles
here
. - Let's put the following code there. The code checks whether the ball is overlapping with either paddle and bounces the ball away when they overlap:
// Variables for checking paddles var ballX = ball.x + ball.speed * ball.directionX; var ballY = ball.y + ball.speed * ball.directionY; // check moving paddle here, later. // check left paddle if (ballX >= pingpong.paddleA.x && ballX < pingpong.paddleA.x ...
Get HTML5 Game Development by Example : Beginner's Guide - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.