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 – connecting the box and two circles with a revolute joint


Carry out the following steps to create a car with the box and wheels:

  1. We are still working only on the logic part. Open our JavaScript logic file in a text editor.

  2. Create a function named createCarAt, which takes the coordinates as arguments. Then, move the body and the wheel creation code in this function. Afterwards, add the following highlighted joint creation code. At last, return the car body:

    function createCarAt(x, y) {
      var bodyDef = new b2BodyDef;
      var fixDef = new b2FixtureDef;
    
      // car body
      bodyDef.type = b2Body.b2_dynamicBody;
      bodyDef.position.x = 50/pxPerMeter;
      bodyDef.position.y = 210/pxPerMeter;
    
      fixDef.shape = new b2PolygonShape();
      fixDef.density = 1.0;
      fixDef.friction = 1.5;
      fixDef.restitution = .4;
      fixDef.shape.SetAsBox(40/pxPerMeter, 20/pxPerMeter);
    
      carBody = carGame.world.CreateBody(bodyDef);
    
      carBody.CreateFixture(fixDef);
    
      // creating the wheels
      var wheelBody1 = createWheel...