I am attempting to create a fixed step loop in my program, but for some reason I just can't seem to get it to work properly. Basically what I need is a loop that does:
while(!over) {
Update(elapsedtime);
Draw(elapsedtime);
}
or something similar, with a . I've tried using Thread.Sleep but I'm not so sure it gave me a real fixed step loop, and when I tried to implement the solution on this website I had problems due to the fact that I couldn't see a way to save the state of the objects affected by the loop. This forced me to exclude that part, which led to slowdown when there were many objects in the loop.
How can I get a fixed step loop without constantly having to save the state of every object in the loop?
If you are working on a game engine, a Timer will probably not work well. Timers do not have enough accuracy to handle a fixed step loop and keep it regular.
You'll need to implement this using a high precision timer. In this case, you'll want to use the Stopwatch class. This will allow you to have enough precision to track your elapsedTime accurately.
You'll just need to keep track of how frequently you want to update (in Ticks), then use a stopwatch to measure the time it takes for each of your updates. After that, you can potentially use a Sleep() call to block, but realize that sleep will only have a precision of 14-15 ms on most systems, even if you only sleep for 0 or 1 ms. This may slow down your loop too much, so you may need to implement a spin lock or similar (while (waiting) { do something }). Sleep() is nice because it saves CPU if you can, the spin lock will eat CPU cycles while you're waiting, but gives you more precision.