HTML and CSS Reference
In-Depth Information
Outputs
This section covers the outputs from your main loop. This includes unseen internal game states as well as audio and
video output.
Game State
Game state is not (directly) displayed to the player. It is used to drive the output that the player sees displayed on the
screen and hears through the speakers. The main loop controls when and at what rate the game state is updated, thus
it is considered an output of the main loop.
Display
The main loop is told when to display the game via requestAnimationFrame . The entire game view should be
rendered whenever requested by the browser.
Audio
Unlike rendering, audio can be scheduled to play in the future by the developer. Inside the frame callback, audio will
be scheduled for playback.
Designing a successful main loop requires understanding and working with the browser, which activates the
main loop with timers, rendering requests, and user input events.
Your First Main Loop and What's Wrong with It
The code snippet in Listing 20-2 is an example of the typical main loop that many programmers start with. It rests
on top of requestAnimationFrame and updates game state and then renders the game before registering for the next
display synchronization signal.
Listing 20-2. Typical main Loop
var lastTime; // null.
void frame(num time) {
if (lastTime == null) {
// Determine an origin in time.
lastTime = time;
// Skip this frame.
window.requestAnimationFrame(frame);
return;
}
// Compute delta time.
var dt = time - lastTime;
lastTime = time;
// Update game.
update(time, dt);
// Render game.
render(time, dt);
// Register for next display signal.
window.requestAnimationFrame(frame);
}
 
Search WWH ::




Custom Search