Semi Fixed-timestep ported to javascript
Posted
by
abernier
on Game Development
See other posts from Game Development
or by abernier
Published on 2012-09-17T13:33:15Z
Indexed on
2012/09/17
15:54 UTC
Read the original article
Hit count: 393
In Gaffer's "Fix Your Timestep!" article, the author explains how to free your physics' loop from the paint one.
Here is the final code, written in C:
double t = 0.0;
const double dt = 0.01;
double currentTime = hires_time_in_seconds();
double accumulator = 0.0;
State previous;
State current;
while ( !quit )
{
double newTime = time();
double frameTime = newTime - currentTime;
if ( frameTime > 0.25 )
frameTime = 0.25; // note: max frame time to avoid spiral of death
currentTime = newTime;
accumulator += frameTime;
while ( accumulator >= dt )
{
previousState = currentState;
integrate( currentState, t, dt );
t += dt;
accumulator -= dt;
}
const double alpha = accumulator / dt;
State state = currentState*alpha + previousState * ( 1.0 - alpha );
render( state );
}
I'm trying to implement this in JavaScript but I'm quite confused about the second while
loop...
Here is what I have for now (simplified):
...
(function animLoop(){
...
while (accumulator >= dt) { // While? In a requestAnimation loop? Maybe if?
...
}
...
// render
requestAnimationFrame(animLoop); // stand for the 1st while loop [OK]
}())
As you can see, I'm not sure about the while
loop inside the requestAnimation one...
I thought replacing it with a if
but I'm not sure it will be equivalent...
Maybe some can help me.
© Game Development or respective owner