HTML5/JS - Choppy Game Loop
Posted
by
Rikonator
on Game Development
See other posts from Game Development
or by Rikonator
Published on 2012-12-13T16:43:59Z
Indexed on
2012/12/13
17:17 UTC
Read the original article
Hit count: 575
I have been experimenting with HTML5/JS, trying to create a simple game when I hit a wall. My choice of game loop is too choppy to be actually of any use in a game.
I'm trying for a fixed time step loop, rendering only when required. I simply use a requestAnimationFrame
to run Game.update
which finds the elapsed time since the last update, and calls State.update
to update and render the current state.
State.prototype.update = function(ms) {
this.ticks += ms;
var updates = 0;
while(this.ticks >= State.DELTA_TIME && updates < State.MAX_UPDATES) {
this.updateState();
this.updateFrameTicks += State.DELTA_TIME;
this.updateFrames++;
if(this.updateFrameTicks >= 1000) {
this.ups = this.updateFrames;
this.updateFrames = 0;
this.updateFrameTicks -= 1000;
}
this.ticks -= State.DELTA_TIME;
updates++;
}
if(updates > 0) {
this.renderFrameTicks += updates*State.DELTA_TIME;
this.renderFrames++;
if(this.renderFrameTicks >= 1000) {
this.rps = this.renderFrames;
this.renderFrames = 0;
this.renderFrameTicks -= 1000;
}
this.renderState(updates*State.DELTA_TIME);
}
};
But this strategy does not work very well. This is the result: http://jsbin.com/ukosuc/1 (Edit).
As it is apparent, the 'game' has fits of lag, and when you tab out for a long period and come back, the 'game' behaves unexpectedly - updates faster than intended.
This is either a problem due to something about game loops that I don't quite understand yet, or a problem due to implementation which I can't pinpoint. I haven't been able to solve this problem despite attempting several variations using setTimeout
and requestAnimationFrame
. (One such example is http://jsbin.com/eyarod/1/edit).
Some help and insight would really be appreciated!
© Game Development or respective owner