Update()
method to the Sprite class:public virtual void Update(GameTime gameTime) { float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; timeForCurrentFrame += elapsed; if (timeForCurrentFrame >= FrameTime) { currentFrame = (currentFrame + 1) % (frames.Count); timeForCurrentFrame = 0.0f; } location += (velocity * elapsed); }
When Update()
is called for the sprite, the standard timing mechanism we have been using is implemented to determine when the frame should be updated. When it is, the frame is set to (currentFrame + 1) % (frames.Count)
. This is a short-hand method of saying "add 1
to the current frame, divide the total by the number of frames in the animation and return the remainder".
As an example, consider an animation with five frames (numbered zero through four). When currentFrame
needs to go from zero to one, the assignment looks like this:
currentFrame = ( 0 + 1 ) % 5
One divided by five is zero, with one as the remainder. When the currentFrame
has reached the last frame of the animation (frame four), the assignment looks like this:
currentFrame = ( 4 + 1 ) % 5
Five divided by five is one, with zero as the remainder. Since the remainder is what we are using as the new currentFrame
, this causes currentFrame
to be reset back to zero to begin the animation loop again.
After currentFrame
has been updated, timeForCurrentFrame
is reset to 0.0f
to begin the animation timing loop over again.
Finally, the Update()
method adds the sprite's velocity
(adjusted for the time elapsed since the last frame) to the sprite's location
. Since velocity
is stored as the change over one second, multiplying it by the gameTime.ElapsedGameTime.TotalSeconds
(which will, if the game is not running slowly, be equal to 1/60th of a second the default update rate for an XNA game) determines the distance moved over a single frame.
Why not just specify velocity
in pixels per frame? In many cases, that may work out just fine, but since you cannot be sure that your game will be running on hardware that can support a full 60 frames per second, if you did not scale your movements to actual elapsed time, your objects would move differently when the game is running at different frame rates, potentially producing a jerky motion.
3.12.108.236