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 – checking a collision between the car and the destination body


Carry out the following steps to handle collision:

  1. Again, we start from our game logic. Open the box2dcargame.js JavaScript file in a text editor.

  2. We set up a destination ground in the ground creation code and assign it to our gamewinWall reference inside the carGame global object instance as follows:

    carGame.gamewinWall = createGround(1200, 215, 15, 25, 0);
  3. Next, we move on to the step function. In each step, we get the complete contact list from the world and check whether any two colliding objects are the car and the destination ground:

    function checkCollision() {
      // loop all contact list 
      // to check if the car hits the winning wall.
      for (var cn = carGame.world.GetContactList(); cn != null; cn = cn.GetNext()) {
        var body1 = cn.GetFixtureA().GetBody();
        var body2 = cn.GetFixtureB().GetBody();
        if ((body1 === carGame.car && body2 === carGame.gamewinWall) || (body2 === carGame.car &&amp...