javascript fixed timestep gameloop with requestanimation frame

Posted by coffeecup on Game Development See other posts from Game Development or by coffeecup
Published on 2012-08-01T14:27:38Z Indexed on 2012/09/01 3:50 UTC
Read the original article Hit count: 453

hello i just started to read through several articles, including

http://gafferongames.com/game-physics/fix-your-timestep/ ...://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step/ ...//dewitters.koonsolo.com/gameloop.html ...://nokarma.org/2011/02/02/javascript-game-development-the-game-loop/index.html

my understanding of this is that i need the currentTime and the timeStep size and integrate all states to the next state

the time which is left is then passed into the render function to do interpolation

i tried to implement glenn fiedlers "the final touch", whats troubling me is that each FrameTime is about 15 (ms) and the update loop runs at about 1500 fps which seems a little bit off?

heres my code

this.t = 0
this.dt = 0.01
this.currTime = new Date().getTime()
this.accumulator = 0.0
this.animate() 

animate: function(){
  var newTime = new Date().getTime()
    , frameTime = newTime - this.currTime
    , alpha
  if ( frameTime > 0.25 ) frameTime = 0.25
  this.currTime = newTime
  this.accumulator += frameTime
  while (this.accumulator >= this.dt ) {
    this.prev_state = this.curr_state
    this.update(this.t,this.dt)
    this.t += this.dt
    this.accumulator -= this.dt
  }
  alpha = this.accumulator / this.dt
  this.render( this.t, this.dt, alpha)
  requestAnimationFrame( this.animate )
}

also i would like to know, are there differences between glenn fiedlers implementation and the last solution presented here ?

gameloop1

gameloop2

[ sorry couldnt post more than 2 links.. ]

edit : i looked into it again and adjusted the values

this.currTime = new Date().getTime()
this.accumulator = 0
this.p_t = 0
this.p_step = 1000/100
this.animate() 

animate: function(){
  var newTime = new Date().getTime()
    , frameTime = newTime - this.currTime
    , alpha

  if(frameTime > 25) frameTime = 25
  this.currTime = newTime
  this.accumulator += frameTime

  while(this.accumulator >= this.p_step){
    // prevstate = currState
    this.update()
    this.p_t+=this.p_step
    this.accumulator -= this.p_step
  }
  alpha = this.accumulator / this.p_step
  this.render(alpha)
  requestAnimationFrame( this.animate )

now i can set the physics update rate, render runs at 60 fps and physics update at 100 fps, maybe someone could confirm this because its the first time i'm playing around with game development :-)

© Game Development or respective owner

Related posts about JavaScript

Related posts about gameloop