2

I am making an XNA game and it's time to make daytime system and for that I need some kind of clock. I tried to use GameTime.TotalGameTime.Milliseconds == 0 to add one second to the second counter of my custom clock class, but it turned out that GameTime doesn't always run through zero milliseconds. Using TimeSpan prevUpdate to compare to TotalGameTime.TotalSeconds doesn't give enough precision, and the time is noticeably slower than the real time somehow.

What XNA or .Net component can I use to base my clock on so that it doesn't cost too much resources or deviates noticeably from real time?

user1306322
  • 8,561
  • 18
  • 61
  • 122

1 Answers1

3

Use Stopwatch for high-precision timing (reference).

Use XNA's GameTime for rendering and frame-to-frame timing logic. XNA's timer does not match "wall clock" time exactly. It is able to drift in order to better line up with frame rendering, giving you smoother animation (this is behaviour is provided by the Game class). Over time it will deviate from real time slightly, but for most games this is not a problem.

Use DateTime for measuring longer time spans accurately (eg: minutes, hours).


Note that you shouldn't compare Milliseconds == 0, because you cannot know exactly when XNA will call your Update method, so you could have Milliseconds == 999 on one frame, and then Milliseconds == 15 the next - wrapping around and skipping past 0, so your condition never triggers.

So you need to determine when the timer crosses the threshold. There are many ways to do this. You could track a threshold (useful if you are tracking some "total" time), incrementing it after each trigger. Personally I prefer to accumulate time like so:

seconds += gameTime.ElapsedTime.TotalSeconds;
if(seconds > 1.0)
{
    seconds -= 1.0;
    DoSomething(); // Triggered each second
}
Community
  • 1
  • 1
Andrew Russell
  • 26,924
  • 7
  • 58
  • 104