FPS independant world stepping

I searched in the past to find a solution to this simple problem: How to make my world step at a same rate independently of the FPS. I tried different approachs like
using dynamic frequency values (calculated using FPS, elapsed time, etc..), exploiting vsync and I finally found the most flexible way of doing it, I wanted to share my code 🙂

This is java code (I use JBox2D now, but this code can be converted to C++)

Code: Select all

        long elapsed = (timeNow - lastTimeUpdate) / (1000 / 250);
        float timeStep = 1.0f / 60;

        if (elapsed > 0) {
            for (int i=0;i<elapsed;i++)
               world.step(timeStep, 10);
           
            lastTimeUpdate = timeNow;
        }


Note: lastTimeUpdate and timeNow contains milliseconds

This code is run on every update interval (in a idle loop for example). In the case of a very low FPS rate (like 10fps), the word.step multiple times in the same update. The result
is a smooth simulation.
http://www.gaffer.org/game-physics/fix-your-timestep

this is what you want to do. The last section that is. It looks like you're doing it right.
This is a weird and long way of achieving FPS independent stepping.

I wrote this code in a project a while ago:
Initialise variables:

Code: Select all

var delta = Date.now();

Then in a loop:

Code: Select all

world.Step((Date.now()-delta)/1000,10,10);
delta = Date.now();

or for variable speed:

Code: Select all

world.Step((Date.now()-delta)*config.SPEED/1000,10,10);



Alternatively you could initialise the variables like:

Code: Select all

var delta = Date.now(), config = { settings... , TIMESTEP: 1/60 }

And in a loop:

Code: Select all

for (var d = (Date.now()-delta)/1000; (d-=config.TIMESTEP)>0; ) world.Step(config.TIMESTEP,10,10);
delta = Date.now();


It's a different language but the method is the same.

Original thread: https://box2d.org/forum/viewtopic.php?t=1186