HTML and CSS Reference
In-Depth Information
main(List<String> args) {
// Setup game.
...
// Startup main loop.
window.requestAnimationFrame(frame);
}
At first glance, the above main loop is quite reasonable, but it has subtle and important flaws. The largest bug is
that it does not have a fixed time step, which means the game logic will run non-deterministically. Non-deterministic
game logic can have real impacts on gameplay. For example, a user on a fast machine may be able to complete the
game but a user on a slower machine may not be able to make a jump or might get stuck in a wall because the time
step used to update the game world changes each frame.
Quest for Determinism
A good main loop provides a deterministic framework that the game-specific logic can be built on. This section
explains how to build a robust main loop that incorporates all input sources and updates the game deterministically.
Fixed Time Step
The first step is to lock the time delta used to update your game state. This means no matter how much time has
elapsed between frame callbacks, the game state is updated as if a fixed amount of time has elapsed, like so:
// Update game.
const fixedDt = 16.0; // milliseconds
update(gameTime, fixedDt);
gameTime += fixedDt;
The above code snippet is sufficient to get deterministic game update behavior but suffers from another problem:
it leaks time. Consider the case when 18 milliseconds elapses between frame callbacks but you only move the game
forward by 16 milliseconds. You've lost 2 milliseconds. Not much time, but the game will lose around 3.6 seconds per
minute. It adds up.
Accumulating Time
The fix for leaking time is straightforward. Extra time must be accumulated across frames and fed back in, like so:
// Compute delta time.
var dt = time - lastTime;
lastTime = time;
accumulatedDt += dt;
const fixedDt = 16.0; // milliseconds
while (accumulatedDt >= fixedDt) {
// Update game.
update(gameTime, fixedDt);
accumulatedDt -= fixedDt;
gameTime += fixedDt;
}
 
Search WWH ::




Custom Search