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?
Use
Stopwatchfor high-precision timing (reference).Use XNA’s
GameTimefor 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 theGameclass). Over time it will deviate from real time slightly, but for most games this is not a problem.Use
DateTimefor 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 yourUpdatemethod, so you could haveMilliseconds == 999on one frame, and thenMilliseconds == 15the 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: