I'm developing a game in C# with Farseer Physics without XNA. I put world.Step(float dt)
in a separated thread in order to keep the form alive (in fact, a while loop would block every other operation). Well, the ball, a dynamic body, runs faster or slower depending on CPU frequency I think. I thought about Thread.Sleep()
with a delay time calculated by reading the CPU frequency and mutiplying it by something, but I'm pretty sure I'm wrong. I'm a little noob. Any suggestion?
Thread.Sleep
is very much not an accurate way to time things. You want to use something like:
Stopwatch timer = new Stopwatch();
timer.Start();
Which you can then use to drive a timed update loop like this:
// Run enough updates to catch up to the current time
private void Idle()
{
double time = timer.Elapsed.TotalSeconds;
accumulatedTime += (time - lastTime);
lastTime = time;
const double frameTime = 1.0/60.0; // 60 frames per second
while(accumulatedTime > frameTime)
{
world.Step((float)frameTime);
accumulatedTime -= frameTime;
}
}
You can then call the above Idle
method followed by a short Sleep
in a loop.
Or you could just call it from an event handler for Application.Idle
- either directly on the UI thread, or by signalling your other thread.