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 + pingpong.paddleA.width) { if (ballY <= pingpong.paddleA.y + pingpong.paddleA.height && ballY >= pingpong.paddleA.y) { ball.directionX = 1; } } // check right paddle if (ballX + pingpong.ball.radius >...