Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing in requestAnimationFrame

In the ongoing construction of my urban transportation model, I am trying to get the timing right.

I would like to be able to

a) Set the animation speed -- I presume it is trying for 60fps right now, but I would like to be able to set it faster or slower. I tried this code:

var fps = 5;
function draw() {
    setTimeout(function() {
       requestAnimationFrame(animate);
  }, 1000 / fps);
}
draw();

but given that rAF is called three different times, I am not sure how to implement it. I tried it on all three, without success.

b) I would like to set a slight delay in the launching of each "vehicle," so that they don't all set out at once.

Fiddle here: https://jsfiddle.net/g3yhr00L/

like image 798
Tyler330 Avatar asked Dec 19 '22 00:12

Tyler330


2 Answers

To throttle the animation, just do this:

// define some FRAME_PERIOD in units of ms - may be floating point
// if you want uSecond resolution
function animate(time) {
    // return if the desired time hasn't elapsed
    if ( (time - lastTime) < FRAME_PERIOD) {
        requestAnimationFrame(animate);
        return;
    }

    lastTime = time;

    // animation code

}

To change the start time of your vehicles, you'd need to build that in the logic of the vehicle itself. I wouldn't animate each vehicle individually.

like image 121
caasjj Avatar answered Dec 21 '22 14:12

caasjj


This is an approach I found when I was also looking to limit FPS.

It is really nice and with exlanation:EDIT: no need to use Date.now().

var fps = 30;
var now;
var then;
var interval = 1000/fps;
var delta;

function draw(now) {
    if (!then) { then = now; }
    requestAnimationFrame(draw);
    delta = now - then;

    if (delta > interval) {
        // update time stuffs

        // Just `then = now` is not enough.
        // Lets say we set fps at 10 which means
        // each frame must take 100ms
        // Now frame executes in 16ms (60fps) so
        // the loop iterates 7 times (16*7 = 112ms) until
        // delta > interval === true
        // Eventually this lowers down the FPS as
        // 112*10 = 1120ms (NOT 1000ms).
        // So we have to get rid of that extra 12ms
        // by subtracting delta (112) % interval (100).
        // Hope that makes sense.

        then = now - (delta % interval);

        // ... Code for Drawing the Frame ...
    }
}

draw();

You can find the original article here: http://codetheory.in/controlling-the-frame-rate-with-requestanimationframe/

like image 20
Saar Avatar answered Dec 21 '22 14:12

Saar