Game Development Reference
In-Depth Information
{
// Send a handshake message.
// Set up game loop.
};
Socket.onmessage = function(E)
{
// Parse the car data from the server.
};
The latter two event handlers require some more detail. When the WebSocket connection succeeds in
opening, the open event is raised, meaning that it is ready to send and receive data. At that point, we want
to send a handshake message to the server telling it the player's name. Then, we'll begin a game loop.
Listing 9-27. WebSocket “open” Event Handler
Socket.onopen = function()
{
// Send a handshake message.
Socket.send(JSON.stringify({ Type: "HI", Data: Name.substring(0, 10) }));
// Set up game loop.
GameTimer = setInterval(
function()
{
// Supposing MyCar is not null, which it shouldn't be if we're
// participating in the game and communicating with the server.
if (MyCar)
{
// Turn and accelerate the car locally, while we wait for the
// server to respond to the key presses we transmit to it.
if (KeysPressed & 2) MyCar.OR -= GP.TurnSpeed;
if (KeysPressed & 4) MyCar.OR += GP.TurnSpeed;
if (KeysPressed & 1)
{
MyCar.VX += GP.Acceleration * Math.sin(MyCar.OR);
MyCar.VY -= GP.Acceleration * Math.cos(MyCar.OR);
}
}
RunGameFrame(Cars);
DrawGame();
},
GP.GameFrameTime);
};
There is not much new in this game loop besides the fact, which must be stressed again, that the game
loop is only being run for a smooth user experience. The actual game logic is being computed on the
server and sent to us. Now we receive and handle the server's game state messages, as shown in Listing
9-28.
 
Search WWH ::




Custom Search