Game Development Reference
In-Depth Information
</body>
</html>
Note This HTML file will be changed to point to client-multiplayer.js instead of client-
local.js when we revisit the game client in a later section.
Now, in client.js, we'll define a few variables specific to the game client, as shown in Listing 9-8.
Listing 9-8. Global Variables in client.js
var GraphicsContext;
var Cars = [];
var MyCar = null;
var KeysPressed = 0; // Bit 0: up. Bit 1: left. Bit 2: right.
GraphicsContext will refer to the HTML canvas 's drawing context, Cars will contain all of the data for the
cars that we'll display to the user, and MyCar will be a reference to that element of Cars that the player is in
control of. The most interesting of these is KeyPressed , and we will discuss it in a moment.
We'll be displaying a little graphic, car.png, and we load it here (see Listing 9-9) so that the browser
caches it.
Listing 9-9. Image Preloading Code
var CarImage = new Image();
CarImage.src = "car.png";
The player will control the car with his arrow keys. We'll make it so that left and right turn the car, while up
makes the car accelerate. In that case, it's necessary to store an orientation for the car, augmenting the
short list of car properties from the previous section. This will be an angle that the car makes with some
arbitrary axis. Pressing left or right increases or decreases the orientation.
In order to process multiple keys at once, we have to think a bit outside the box—simply responding to
keydown events is not sufficient here. What we need to know during a given game frame is whether those
three keys are pressed down or not. The KeysPressed variable will serve that purpose. We'll use its bits as
flags, setting bit #0 if the up key is pressed down, bit #1 if the left key is pressed down, and bit #2 if the right
key is pressed down. If this is unfamiliar to you, imagine we have three light switches, each going on when a
certain key is pressed down and going off when that key is released. The KeysPressed variable keeps track of
which lights are on. The event handlers to achieve this functionality are as shown in Listing 9-10.
Listing 9-10. Handling Keyboard Input
document.addEventListener("keydown",
function(E)
{
if (E.which == 38 && (KeysPressed & 1) == 0) KeysPressed |= 1; // Up.
else if (E.which == 37 && (KeysPressed & 2) == 0) KeysPressed |= 2; // Left.
else if (E.which == 39 && (KeysPressed & 4) == 0) KeysPressed |= 4; // Right.
}
 
Search WWH ::




Custom Search