Help needed to control the frame rate

I am developing a game, but the frame rate varies from computer to computer. I wrote a function for reducing the frame rate to 60 frames per second for any machine, but the result is studdering animation even for high performance PCs.

Could you please help? Below is the code. The top function is responsible for reducing the frame rate by sleeping for a few milliseconds when the time to execute the display function is less than 16.6666 miliseconds. The bottom function is obviously the Display function called from main by the main loop.

SYSTEMTIME now;
float desiredMillisecsPerFrame = 16.666666f;

void ModifyFrameRate(){
SYSTEMTIME old = now;
GetSystemTime(&now);

float millisecsOld = old.wMilliseconds;
float millisecsNow = now.wMilliseconds;

if(millisecsOld > millisecsNow){
	millisecsNow += 1000;
}

float difference = millisecsNow - millisecsOld;

if(desiredMillisecsPerFrame > difference){
	Sleep(desiredMillisecsPerFrame - difference);
}

}

void displayPrimary(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

levels.DisplayCurrentLevel();

ModifyFrameRate();

glutSwapBuffers();
glFlush();

}

Browse around here for the answer, it’s been answered almost every couple days.

First of all, remove the glFlush() because it is
not only useless where it is (since the buffer swap
does a flush automatically if I am not mistaken),
but it might be responsible for some framerate
reduction. Check on this one.

You are on the right direction. All you need to do
is allow for the GL to render no faster than the
time interval corresponding to the desired framerate.

Search for a topic saying something like “clamping
framerate.”

You are dooing it backward. Let the frame rate be as fast as it can be, and scale the animation to match the time between frames.

In a multiplayer game this could be problematic, because you get different results in numeric integration when using different framerates (see Quake 3, some moves are only possible with certain framerates).

A solution would be to render as fast as possible but calculate using a fixed physics framerate. This way it could be necessary to calculate more than one physics frame per graphics frame, but this way you get consistent results while still rendering as fast as possible.

I would recommend using a different thread for doing
physics than you do for the graphics. It makes sense
and it should be the way to go, particularly on multi
processor machines. I do that.

But on multiplayer games, it also makes sense to have
one machine doing all the physics and simply passing
the state of the world to other machines in a sequence
of packets over some UDP-like network layer.
And of course, I could be wrong…

Oh wow! Thanks a lot, guys!