Ionut Eugen
Ionut Eugen

Reputation: 501

Animation alternatives Javascript

So I want to make a small JavaScript game. And in order to do that I need to animate a few things. I went researching and found about setInterval and requestAnimationFrame.

I can use either of those 2 for making my game work, however I understood that requestAnimationFrame is the better alternative there. The problem I see with this is that while the function has its benefits , you are unable to set a framerate , or an update rate for it easily.

I found another thread that explained a way of making this work however it seemed somewhat complicated.

Controlling fps with requestAnimationFrame?

Is there an easier way of animating with a set framerate ?

Upvotes: 0

Views: 1949

Answers (1)

philipp
philipp

Reputation: 16505

Is there an easier way of animating with a set framerate ?

Simply put: no. Since rendering is one of the most computation heavy process for a browser, which can be triggered in various ways, it is not possible to foretell how long an update will take, since it can range from drawing one circle on a canvas up to a complete replace of all the visible content of the page.

To overcome this, browser offer a way to call a function a often as possible and the developer is responsible to make his animation sensitive to different time deltas/time steps.

One way to tackle that is to use the concept of velocity. velocity = distance / time. If you want an asset to have a constant velocity you can do the following, since distance = velocity * time follows:

var 
  asset_velocity = 1; //pixel per millisecond
  last = new Date().getTime()
;

(function loop () {
  var 
    now = new Date().getTime(),
    delta = now - last,
    distance = asset_velocity * delta
  ;

  //update the asset
  last = now;
  window.requestAnimationFrame(loop)
})();

Upvotes: 2

Related Questions