Time for action – updating the Sprite

  1. 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 ...

Get XNA 4.0 Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.