Time for action – updating the Sprite
Add the
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); }
What just happened?
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...