Time for action – adding force to the car
Carry out the following steps to take the keyboard input:
- Open the
box2dcargame.js
JavaScript file in a text editor. - 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; } });
- 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...