views:

75

answers:

2

So in my game I need to simulate the physics in a hardware independent manner.

I'm going to use a fixed time-step simulation, but I need to be able to calculate how much time is passing between calls.

I tried this and got nowhere:

#include <time.h>
double time_elapsed;
clock_t last_clocks = clock();
while (true) {
  time_elapsed = ( (double) (clock() - last_clocks) / CLOCKS_PER_SEC);
  last_clocks = clock();
  printf("%f\n", time_elapsed);
}

Thanks!

A: 

clock_gettime(3).

Nikolai N Fetissov
+2  A: 

You can use gettimeofday to get the number of seconds plus the number of microseconds since the Epoch. If you want the number of seconds, you can do something like this:

#include <sys/time.h>
float getTime()
{
    struct timeval time;
    gettimeofday(&time, 0);
    return (float)time.tv_sec + 0.000001 * (float)time.tv_usec;
}

I misunderstood your question at first, but you might find the following method of making a fixed-timestep physics loop useful.

There are two things you need to do to make a fixed-timestep physics loop.

First, you need to calculate the time between now and the last time you ran physics.

last = getTime();
while (running)
{
    now = getTime();
    // Do other game stuff
    simulatePhysics(now - last);
    last = now;
}

Then, inside of the physics simulation, you need to calculate a fixed timestep.

void simulatePhysics(float dt)
{
    static float timeStepRemainder; // fractional timestep from last loop
    dt += timeStepRemainder * SIZE_OF_TIMESTEP;

    float desiredTimeSteps = dt / SIZE_OF_TIMESTEP;
    int nSteps = floorf(desiredTimeSteps); // need integer # of timesteps

    timeStepRemainder = desiredTimeSteps - nSteps;

    for (int i = 0; i < nSteps; i++)
        doPhysics(SIZE_OF_TIMESTEP);

}

Using this method, you can give whatever is doing physics (doPhysics in my example) a fixed timestep, while keeping a synchronization between real time and game time by calculating the right number of timesteps to simulate since the last time physics was run.

Jordan Lewis
now - last keeps on returning 0. :( . float now = get_time(); float time_elapsed = now - last_time; printf("%f\n", time_elapsed); last_time = now; usleep(1000000); prints 0.00000, 0.0000, ...
Alexandre