Jump to content
  • Advertisement
Sign in to follow this  
BUnzaga

HTML5+Canvas Game Loop Critique

This topic is 2430 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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...

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!