HTML5 Games and Consistent Timers

Due to the wide array of CPUs, graphics cards, and hardware acceleration options, HTML5 games need to deal with varying performance conditions.  This implies that HTML5 games need to track their internal game times to ensure everything happens in a predictable and deterministic manner.

An "internal game time" is a clock that the game maintains, independent of the system's clock.  The internal game time can start at zero when the game starts and tick itself forward as the game progresses.

To illustrate why the internal game time is important, consider the case of requestAnimationFrame.  Both Chrome and Mozilla have implemented requestAnimationFrame, a mechanism to hand off the animation frequency and sync to the browser.  This is A Good Thing, because the browser reduces or eliminates tearing effects because requestAnimationFrame is called when the browser is ready to paint the screen.

requestAnimationFrame is also very smart, as the browser will not run animations or paint the screen if the tab or animated element itself is not visible.  This greatly reduces CPU usage and increases battery life, both very good things!  However, this implies that the game itself pauses when it's not in view.

If the game can pause, and your game is using standard system times, then you will have a big problem.  When you calculate your delta time, the time between last check and this check, right after you come back to life after a pause, then the delta time will be huge.  And this means your game will skip ahead many many frames.  This means, not only will the user be confused by the big leap through time, but any events that should have happened will be missed and skipped.

You can avoid this by using your own internal game timer, which clamps the delta time to a known, fixed rate.  This solves the pause problem, as any pause length will be clamped to maxStep when the game wakes back up.

Finally, here's some example code:


Timer.prototype.step = function() {
        var current = Date.now();
        var delta = (current - this.lastTimestamp) / 1000;
        this.gameTime += Math.min(delta, this.maxStep);
        this.lastTimestamp = current;
}


Or, you could not worry about and get a game library that does this for you, like Impact.

Popular posts from this blog

Lists and arrays in Dart

The 29 Healthiest Foods on the Planet

Converting Array to List in Scala