atech1118
atech1118

Reputation: 11

Javascript - requestAnimationFrame Frame Rate

I have a sprite sheet animation where I am using requestAnimationFrame method to animate a spritesheet with only 4 images on the sheet This is my code: http://hyque.com/ryan/ani-ryan-2.html The problem is that it is too fast at 60 fps, so I want to slow the fps. I have been reading several articles on different ways to do it using either setInterval or Date(). I can’t seem to get the code to work correctly. Can anyone help, please. Here is one of the articles that I tried to merge into my code: http://codetheory.in/controlling-the-frame-rate-with-requestanimationframe/

Upvotes: 0

Views: 1314

Answers (2)

Inkh Su Tesou
Inkh Su Tesou

Reputation: 372

Generally, for Game Engines you will want your rendering speed to be different from your logic speed.

Logic speed should simply be as fast as possible

setInterval( logic, 0 ); // runs as fast as possible

OR

setTimer( logic, 0 ); // logic() runs this again ( i think this is generally better )

Whereas render should remain as you have it, as fast as rendering is done

requestAnimationFrame( render ) // per render frame

However, requestAnimationFrame is unstable between machines, and for the most part will run 60 frames per second ( depending on the users hardware ).

In this case, for consistency you should base your animation on consistent TIME or setTimeout.

In your animation you could use something like

var date = new Date(), // date object

milliseconds = date.getMilliseconds(), // 0 - 999 of the second

totalSpriteFrames = 4

frame = Math.floor( milliseconds / ( 1000 / totalSpriteFrames ) ); // break the second into four frames

Create the date object outside of your animation scope for optimization, and this math can easily be used to choose which " frame " your sprite is on. You can also use this for multiple sprites, just change their " totalSpriteFrames "

This is also scalable in case you end up with a frame heavy sprite with many frames.

Upvotes: 0

ZergRush
ZergRush

Reputation: 117

So what I like to use to control animation apart form the "game loop."

var lastRender = 0;
var counter = 0;
function render(time)
{
    //checks to see if enough time has passed
    if(time - lastRender<16){requestAnimationFrame(render);return;}
    lastRender = time;
    counter++;
    if(counter %20 && counter != 0)
       animation();
    if(counter >= 60)
         counter=0;
    requestAnimationFrame(render);
}
requestAnimationFrame(render);

This gives you greater control over your sprites so you can now have them at different speeds and your logic stays at 60fps.

Upvotes: 4

Related Questions