I am currently on chapter 3 of the book "Learning XNA 4.0". At the end of this chapter is a section on changing the animation speed of sprites.

timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
   if (timeSinceLastFrame > millisecondsperFrame)
       timeSinceLastFrame -= millisecondsperFrame;
       //code for cycling through sprite sheet here.

This code is in the Update method. It iterates timeSinceLastFrame until it's greater than millisecondsperFrame (which I have specified as 20), and then it resets by subtracting millisecondsperFrame from timeSinceLastFrame.

If I instead reset it by writing timeSinceLastFrame = 0, the animation is noticeably slower. From what I can tell, this is due to the fact that XNA updates at 60 frames per second, so timeSinceLastFrame iterates by several milliseconds each time, and likely won't have the same value as millisecondsperFrame once the if statement compares the two.

Despite this, is there anything particularly bad about writing timeSinceLastFrame = 0? Or is timeSinceLastFrame -= millisecondsperFrame safer?


1 Answer 1


The reason why timeSinceLastFrame -= millisecondsperFrame works better is it accommodates for the bleed-over time from the animation. Let me explain:

So your game is running and the Update method is firing. When it reaches a point where it advances to the next frame, it will reset using the form mentioned above. Say your animation advances every .3 seconds, and the update method has fired at the .32 second mark. Therefore, .02 seconds are carried over to the next frame.

So what happens when you set timeSinceLastFrame to 0? Well then at .32 seconds when the frame advances, it resets the timer meaning you just spent an extra .02 seconds on a frame. If this happens say 30 times, you have just created a lag time of over half a second. The accumulation of lag time slows down the animation, and that causes the effect you see there.

Generally, if you want more accurate animation, I would go with the method that's currently there in your code.

Happy Coding!

  • \$\begingroup\$ Your explanation makes complete sense. Thank you very much! \$\endgroup\$
    – AsianBorat
    Commented Jan 14, 2012 at 4:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .