Game Development Reference
In-Depth Information
The only remaining piece of server.js is the game loop (see Listing 9-23). We already constructed a game
loop in client.js, and this one will be very similar.
Listing 9-23. Setting up the Game Loop on the Server
// Set up game loop.
setInterval(function()
{
// Make a copy of the car data suitable for RunGameFrame.
var Cars = [];
for (var ID in Connections)
{
var C = Connections[ID];
if (!C.Car) continue;
Cars.push(C.Car);
if (C.KeysPressed & 2) C.Car.OR -= Game.GP.TurnSpeed;
if (C.KeysPressed & 4) C.Car.OR += Game.GP.TurnSpeed;
if (C.KeysPressed & 1)
{
C.Car.VX += Game.GP.Acceleration * Math.sin(C.Car.OR);
C.Car.VY -= Game.GP.Acceleration * Math.cos(C.Car.OR);
}
}
Game.RunGameFrame(Cars);
// Increment the game frame, which is only used to time the SendGameState calls.
Frame = (Frame + 1) % FramesPerGameStateTransmission;
if (Frame == 0) SendGameState();
},
Game.GP.GameFrameTime
);
The variables exported from game.js are referenced as Game.RunGameFrame and Game.GP , where Game was
defined all the way at the top of server.js when we called require() .
Now all of server.js is put together, but our game client is stuck in the Stone Age. Time to bring it online!
The game client, Part 2
The game client is going to assume a subordinate role now that we have an authoritative server. Every
time the server calls SendGameState() , the game client will receive the list of car data and overwrite
whatever it had previously. We still have a game loop and still respond to keyboard input, but only to make
the game experience smoother as we discussed in an earlier section. The main client changes, therefore,
are to establish a WebSocket connection and then handle messages from the server, and to pass along
keyboard data to the server.
As shown in Listing 9-24, we'll keep two global variables more than we had in the old game client.
 
Search WWH ::




Custom Search