HTML and CSS Reference
In-Depth Information
Detecting and classifying user input is done on the queue of input events and is game-specific. For example, a
first person shooter game needs to know if the W, A, S, or D keys are down and how much the mouse has moved since
the last frame. The main loop is only responsible for providing the buffer of input events to the game.
Timers
The internal game clock ( gameTime ) is managed by the main loop. Any in-game timers, such as the timer tracking the
door that stays unlocked for two seconds after the player steps from a pressure plate, must be kept in sync with
the game clock. If the in-game timers used a different clock than the game update, the timers would not fire when
expected. You can solve this by moving the timer time forward inside the main loop, like so:
// Compute delta time.
var dt = time - lastTime;
lastTime = time;
accumulatedDt += dt;
const fixedDt = 16.0; // milliseconds
if (accumulatedDt > 2.0 * fixedDt) {
// Lose time.
accumulatedDt = 2.0 * fixedDt;
}
while (accumulatedDt >= fixedDt) {
// fire timers.
fireTimers(gameTime, fixedDt);
// Update game.
update(gameTime, fixedDt);
accumulatedDt -= fixedDt;
gameTime += fixedDt;
}
Include support for both periodic (repeating) and single shot timers as well as support for cancelling timers.
Rendering
The final task of the main loop is to trigger rendering of the game. Rendering is always done in the frame callback,
which is synchronized with the browser's own rendering pipeline.
On Demand
Rendering is done on demand and initiated when the browser invokes the frame callback registered with window.
requestAnimationFrame . After updating the game timers and state, the game is rendered. When the browser tab
holding the game is not focused, the rate at which the frame callback is executed drops, possibly to 0.
Interpolation
Consider what happens when the render frame callback is fired but the accumulated time is not enough to trigger a
game logic update. The render is supposed to use the current state, but the game state is from the past (see Figure 20-1 ).
It is possible to compensate for this by projecting the game object's display transformation from the last game update
to the current time. This can be done either through interpolation or extrapolation.
 
Search WWH ::




Custom Search