This question is specific to reactive-banana and real-time simulations with a physical and visual component (eg., games).
According to Fix Your Timestep! the ideal way to setup a game loop (assuming physics that needs to be reproducible), you need a fixed timestep between frames. After considering a number of real complications , the author arrives at this game loop:
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 );
}
The synopsis is that the physics simulation is always fed the same increment of time (dt
) for numerical stability. Arranging for that must consider that physics and visuals may update at different frequencies and you don't want to get too far behind.
For example, you may want updates at a frequency of 20hz, but a visual update with a framerate of 60hz. This loop does linear interpolation of the physics to make up the difference between physics updates and graphical updates.
Additionally, when the difference in time between frames is much larger than dt
there is a loop to handle stepping the updates in chunks of dt
. The note about the spiral of death just refers to a case when your physics calculation simply can't keep up with the desired frequency of updates, so you allow it to skip some updates.
For this discussion, the part I'm most interested in is arranging so that the call to the physics engine (the call to integrate
) is always stepped by dt
. Does reactive-banana allow the user to write this style loop? If so how? Perhaps an example doing real-time physics simulation is in order (or already exists)?