How To: Animate a Sprite

Demonstrates how to animate a sprite from a texture using a custom class.

The source code in this example assumes the texture you are loading is a strip of equal-sized images. In this example, the texture is a 256×64 texture with four frames. This example uses a class named AnimatedTexture, which is included with the sample.

The Complete Sample

The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Drawing an Animated Sprite

To draw an animated sprite

  1. Follow the steps of How To: Draw a Sprite.

  2. In your game's constructor, create an instance of the AnimatedTexture class.

    This example uses (0,0) as the origin of the texture, no rotation, a scale of 2, and a depth of 0.5.

            private AnimatedTexture SpriteTexture;
            private const float Rotation = 0;
            private const float Scale = 2.0f;
            private const float Depth = 0.5f;
            public Game1()
                SpriteTexture = new AnimatedTexture(Vector2.Zero, Rotation, Scale, Depth);
    #if ZUNE
                // Frame rate is 30 fps by default for Zune.
                TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0);
  3. Load the texture or textures that provide the image data for the animation.

    In this example, the AnimatedTexture class loads a single texture and divides it into frames of animation. It uses the last parameter to determine how many frames to draw each second. In this case, it draws four frames at 2 fps (frames per second).

    private Viewport viewport;
    private Vector2 shipPos;
    private const int Frames = 4;
    private const int FramesPerSec = 2;
    protected override void LoadContent()
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        // "shipanimated" is the name of the sprite asset in the project.
        SpriteTexture.Load(Content, "ship", Frames, FramesPerSec);
        viewport = graphics.GraphicsDevice.Viewport;
        shipPos = new Vector2(viewport.Width / 2, viewport.Height / 2);
  4. In your game's Update method, determine which frame of animation to display.

    protected override void Update(GameTime gameTime)
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        // TODO: Add your game logic here.

    This is handled by AnimatedTexture's UpdateFrame method, which takes the elapsed seconds between updates as a parameter.

    // class AnimatedTexture
    public void UpdateFrame(float elapsed)
        if (Paused)
        TotalElapsed += elapsed;
        if (TotalElapsed > TimePerFrame)
            // Keep the Frame between 0 and the total frames, minus one.
            Frame = Frame % framecount;
            TotalElapsed -= TimePerFrame;
  5. In your game's Draw method, call Draw on the AnimatedTexture object.

    protected override void Draw(GameTime gameTime)
        // TODO: Add your drawing code here
        SpriteTexture.DrawFrame(spriteBatch, shipPos);

    AnimatedTexture will draw the sprite using the subrectangle of the texture that contains the desired animation.

    // class AnimatedTexture
    public void DrawFrame(SpriteBatch batch, Vector2 screenPos)
        DrawFrame(batch, Frame, screenPos);
    public void DrawFrame(SpriteBatch batch, int frame, Vector2 screenPos)
        int FrameWidth = myTexture.Width / framecount;
        Rectangle sourcerect = new Rectangle(FrameWidth * frame, 0,
            FrameWidth, myTexture.Height);
        batch.Draw(myTexture, screenPos, sourcerect, Color.White,
            Rotation, Origin, Scale, SpriteEffects.None, Depth);

Community Additions