I am currently re-writing my “extension code base” (would not call it engine ) and I am testing my AnimatedSprite class. In its Update method, I am tracking the elapsed time by adding the gameTime.ElapsedTime.Milliseconds to a private float variable, and when it reaches a specific amount I play the next frame. It works fine at 60 fps, but at the moment I only display 2 test animation and the fps is around 3500. Therefore the ElapsedTime.Milliseconds is always 0, so I am adding 0 to the variable, so it remains 0, therefore the animation does not even start.
My question: although I am happy with the 60fps settings, but is there a “better” way to track the elapsed time?
Use a TimeSpan to track time. ex.:
TimeSpan t;
// in update
t+=gameTime.ElapsedTime;
Or use TimeSpan.Ticks. One tick is 1/10000ms or something, it might be platform-specific.
TimeSpan wraps this number and convert it to/from Minutes/Seconds/msecs/etc.
There are all the overloads you need to add/sub between TimeSpan and DateTime.
Use the TotalSeconds or TotalMilliseconds properties, since they count whole and fractional parts. The Milliseconds property only counts whole milliseconds. 3500fps means 1/3500 sec per frame. That is less than 1 ms which is 1/1000 sec, and since the Milliseconds property is an integer, it gets rounded down to zero. The TotalMilliseconds property will return the fractional part of the millisecond as well.
Thanks, I tried it and works fine with all settings. This is now how I “calculate” when do I need to show the next frame:
float AnimationTimer = 0.0f;
...
public void Update(...)
{
//CurrentAnimation.DelayUntilNextFrame = the delay in milliseconds between
//the current frame and the next one.
if (AnimationTimer < CurrentAnimation.DelayUntilNextFrame)
AnimationTimer += (float)(gameTime.ElapsedGameTime.TotalMilliseconds %
CurrentAnimation.DelayUntilNextFrame);
else
{
AnimationTimer = 0.0f;
//Show next frame...
}
}