Game Development Reference
In-Depth Information
);
document.addEventListener("keyup",
function(E)
{
if (E.which == 38) KeysPressed &= ~1; // Up.
else if (E.which == 37) KeysPressed &= ~2; // Left.
else if (E.which == 39) KeysPressed &= ~4; // Right.
}
);
The & and | are the “bitwise and” and “bitwise or” operators, respectively. Once the page loads, we get our
drawing context from the canvas and then proceed into the game loop, as shown in Listing 9-11.
Listing 9-11. Starting the Game Loop on Window Load
window.addEventListener("load",
function()
{
var BumperCanvas = document.getElementById("BumperCanvas");
BumperCanvas.width = GP.GameWidth;
BumperCanvas.height = GP.GameHeight;
GraphicsContext = BumperCanvas.getContext("2d");
// Set up game loop.
setInterval(
function()
{
if (MyCar)
{
if (KeysPressed & 2) MyCar.OR -= GP.TurnSpeed; // Turn left.
if (KeysPressed & 4) MyCar.OR += GP.TurnSpeed; // Turn right.
if (KeysPressed & 1) // Accelerate.
{
MyCar.VX += GP.Acceleration * Math.sin(MyCar.OR);
MyCar.VY -= GP.Acceleration * Math.cos(MyCar.OR);
}
}
RunGameFrame(Cars);
DrawGame();
},
GP.GameFrameTime);
}
);.
What you see in Listing 9-11 is the entire game loop. Every 20 milliseconds (this value is stored in
GP.GameFrameTime ), we process the input captured in Listing 9-11 (the OR property of a car is its
orientation), run a game frame (that method belongs to game.js), and then draw the game. When the up
key is pressed, the car accelerates along the car's current orientation. The factors of sine and cosine can
be understood with a little bit of geometry, taking into account the wonky HTML canvas coordinates where
the positive y direction is down and angles are measured clockwise.
 
Search WWH ::




Custom Search