Book Image

HTML5 Game Development by Example: Beginner's Guide

By : Seng Hin Mak
Book Image

HTML5 Game Development by Example: Beginner's Guide

By: Seng Hin Mak

Overview of this book

Table of Contents (18 chapters)
HTML5 Game Development by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
9
Building a Physics Car Game with Box2D and Canvas
Index

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:

  1. Open the js/pingpong.js file that we used in the previous section.

  2. In the moveBall function, we have already reserved the place to put the collision detection code there. Find the line with // check paddles here.

  3. 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 >...