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 = clo开发者_开发知识库ck();
while (true) {
time_elapsed = ( (double) (clock() - last_clocks) / CLOCKS_PER_SEC);
last_clocks = clock();
printf("%f\n", time_elapsed);
}
Thanks!
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.
clock_gettime(3)
.
精彩评论