HTML5+Canvas Game Loop Critique

Started by
1 comment, last by swiftcoder 12 years, 3 months ago
I have been working on this for a while now, going back and forth between several game loops, and I finally found one that I am happy with (for now). It looks a bit extravagant, but... whatever.

I have tested it with Chrome 15.0.874.x, Firefox 8.0, and IE 9.0.8.x and no issues so far (except with my lame collision detection). I also tried it with my Droid phone, and although the FPS is pretty low, it still works ok.


This is a 'frame rate independent' game loop for HTML5 Canvas.


// earlier in code: setInterval(GameLoop, 1)

var FPS = 60; // fps
var PS = 1/FPS; // physics step
var last = Date.now()/1000;
var accrued = 0.0; // accrued time (betwen physics steps)


var GameLoop=function(){
if(false == _this.paused){
var now = Date.now()/1000;
var dt = ((now-last) > .2) ? .2 : now-last; // time between frames
last = now;
accrued += dt; // add dt to accrued
if(dt > PS){ // if dt is more than a physics step
Update(dt-(accrued-PS)); // bring positions up to 1 full physics step
CheckCollisions(); // check collisions
accrued -= PS; // deduct 1 physics step from time
while(accrued >= PS){ // if accrued still greater tha a physics step
Update(PS); // move positions ahead 1 step
CheckCollisions(); // check collisions
accrued -= PS; // deduct 1 physics step from accrued
}
dt = accrued;
}
else{ // if dt is less than a physics step
if(accrued >= PS){ // if accrued time is more than a physics step
Update(dt-(accrued-PS)); // bring positions up to one full physics step
CheckCollisions(); // check collisions
accrued -= PS; // deduct the physics step from accrued
dt = accrued;
}
}
}
else{
last = Date.now()/1000; // for paused game
}
if(dt > 0.0){
Update(dt);
}
Render(); // render images
}


You can see it in action on my ... 'game_1' demo: http://www.html5.bun...me_1/game1.html

FYI, I disabled the right mouse click, just for future game ideas. I'll be putting in sounds and animated images / particles and emitters soon...

Please let me know what you think...
Advertisement
I made a couple minor changes... Has anyone tried to implement this yet? Any good or bad experiences? I was hoping to get a little feedback.
Your demo seems to work ok. Not really sure what else there is to say about it... That looks like a pretty standard main loop, overall.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

This topic is closed to new replies.

Advertisement