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

Get HTML5 Game Development by Example : Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.