Game Development Reference
In-Depth Information
With a little bit of clairvoyance, we begin the game engine, game.js, with the list of game properties that
we'll need (see Listing 9-1). These will, in the final product, apply simultaneously to the client and the
server. There is certainly virtue in not having two such lists maintained separately.
Listing 9-1. Global Properties of the Game
var GP =
{
GameWidth: 700, // In pixels.
GameHeight: 400, // In pixels.
GameFrameTime: 20, // In milliseconds.
CarRadius: 25, // In pixels.
FrictionMultiplier: 0.97, // Unitless
MaxSpeed: 6, // In pixels per game frame.
TurnSpeed: 0.1, // In radians per game frame.
Acceleration: 0.3 // In (pixels per game frame) per game frame.
};
Now, in Listing 9-2, let's outline the code for the game loop method, RunGameFrame(Cars) . The argument,
Cars , will be a collection of the car data, namely their positions and velocities. Those two pieces of
information, in some sense, are the car: they are all we need, internally, to keep track of. We'll store cars
as simple JavaScript objects: { X, Y, VX, VY } . We will add some properties later on, but these are the
only essentials. The position will be in pixels and the velocity will be in pixels per “game frame.” A game
frame is the basic unit of timing that we use. It means, simply, one iteration of the game loop.
Tip In general, timing for logic in your game should be done by counting game frames
and not by using built-in timing functions such as JavaScript's
setInterval
. Those
functions will be irregular depending on CPU load, browser throttling, and so forth. While
that is not a bad thing in and of itself, you will have a hard time giving a consistent game
experience for different users unless you do your timing by counting game frames.
In each game frame, we have to
update the cars' positions
check for collisions after they're in their new positions
react to those collisions
Listing 9-2. Outline of RunGameFrame
function RunGameFrame(Cars)
{
// Move the cars and collect impulses due to collisions.
// Apply impulses.
// Enforce speed limit and apply friction.
}
 
Search WWH ::




Custom Search