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 – adding force to the car


Carry out the following steps to take the keyboard input:

  1. Open the box2dcargame.js JavaScript file in a text editor.

  2. In the page loaded event handler, we add the following keydown event handler at the beginning of the code. This listens to the right arrow key and the left arrow key to apply force in different directions:

    $(document).keydown(function(e){
      switch(e.keyCode) {
        case 39: // right arrow key to apply force towards right
          var force = new b2Vec2(100, 0);
          carGame.car.ApplyForce(force, carGame.car.GetWorldCenter());
          return false;
          break;
        case 37: // left arrow key to apply force towards left
          var force = new b2Vec2(-100, 0);
          carGame.car.ApplyForce(force, carGame.car.GetWorldCenter());
          return false;
          break;
      }
    });
  3. We have added forces to bodies. We need to clear forces in each step, otherwise the force accumulates:

    function updateWorld() {
      // existing code goes here.
      // Clear previous applied...