Game Development Reference
In-Depth Information
Now, the only thing missing from this non-multiplayer client is to draw the game. Listing 9-12 is a
straightforward exercise in using the canvas .
Listing 9-12. DrawGame method
function DrawGame()
{
// Clear the screen
GraphicsContext.clearRect(0, 0, GP.GameWidth, GP.GameHeight);
for (var i = 0; i < Cars.length; i++)
{
GraphicsContext.save();
GraphicsContext.translate(Cars[i].X | 0, Cars[i].Y | 0);
GraphicsContext.rotate(Cars[i].OR);
GraphicsContext.drawImage(CarImage, -CarImage.width / 2 | 0,
-CarImage.height / 2 | 0);
GraphicsContext.restore();
}
}
There are a few interesting points to be raised here:
The x | 0 trick takes the integer part of the number x (and it's much faster than Math.round , etc.).
In current implementations of canvas , content may be drawn either aliased or anti-aliased
depending on whether the command specifies integer or fractional pixel values. It is a good idea
to only draw at integer values so that the moving car's appearance doesn't change as it moves
through non-integer coordinates.
Saving and restoring canvas state is very useful, and a good habit to have.
The client is done! Load it up, and it does... nothing. Well, there are no cars. So, let's add some cars to test
it out.
Listing 9-13. Initializing the Local Client with Some Cars
Cars.push({ X: 200, Y: 200, VX: 0, VY: 0, OR: 0 });
Cars.push({ X: 100, Y: 100, VX: 5, VY: 0, OR: 0 });
Cars.push({ X: 300, Y: 300, VX: -1, VY: -1, OR: Math.PI });
MyCar = Cars[0];
This code can go anywhere that's not in a function, so put it at the end of the file. Next we'll implement the
server using node.js and then revisit the game client in order to bring it online.
 
Search WWH ::




Custom Search