rezoner / CanvasQuery

Canvas for 2d gamedevelopers. Out of box canvas, keyboard, mouse, events.
http://canvasquery.com
586 stars 52 forks source link

Irregular .onStep() updates #13

Closed florian-s-code closed 11 years ago

florian-s-code commented 11 years ago

Hi,

I get strange results when I use .onStep(). It sometimes updates very fastly, sometimes very slowly and it sometimes begins very fast and then becomes slow after a random time (delta from 5 to >30).

A simple requestAnimationFrame() gives me regular updates on an attempt and on each attempts. Comparison test : http://cssdeck.com/labs/w6wdovya

rezoner commented 11 years ago

onStep is based on interval which is set to 25 onRender is using requestAnimationFrame which will run as fast as possible

You should use delta in your formulas like

x += speed * delta / 1000;

Speed is in pixels per second. Try to put that in both render and step and you will notice that they go at the same speed.

florian-s-code commented 11 years ago

Thank you for your reply, I should have used delta before but I was missing a formula so double thanks.

But why don't the 2 methods use requestAnimationFrame ?

rezoner commented 11 years ago

Well this is really simple.

When you change the tab in the browser. requestAnimationFrame stops - which is something you really want because it also stops to drain users CPU but the setInterval is still going - that's why we use it for logic update - because usually you want the game to proceed - same as you are alt-tabbing in windows.

Why not put logic in animationFrame? Because logic can be really heavy - for example when using physics - and you don't need 60 updates per second for physics - it could just kill the performance.

ps: well you can decrease FPS rate manually in requestAnimationFrame, so this is not 100% accurate answer :)

florian-s-code commented 11 years ago

I was using requestAnimationFrame for everything, thinking it would boost my games' performance but it was not the right way of using it. Thanks for the explanation.