Josh-CO Dev

Solving the worlds problems one line of code at a time.

XNA – Sprite Sheet Animation

Leave a comment


Dug this article out from the old archives and thought I would post it here. Context might not make sense, but the basic code should work all the same. You can tie this into the tile engine tutorial.

Haven’t had too much time to do any programming this week, but I did just convert my player animation engine to animate a sprite based on a sprite sheet rather than a horizontal imageset. Here is the relevant code.

I realize that this needs to be more object oriented, but I’ll get there.
This is added to the animated sprite class:

public int YFrame
        {
            get { return yFrame; }
            set { yFrame = value; }
        }
        int yFrame = 0;

All the rest of the code is in the player class

private void AnimateLeft(GameTime gt)
        {
            if (currentKBState != previousKBState)
            {
                //CurrentFrame = 5;
                CurrentFrame = 0;
                YFrame = 1;
            }

            Timer += (float)gt.ElapsedGameTime.TotalMilliseconds;

            if (Timer > Interval)
            {
                CurrentFrame++;

                //if (CurrentFrame > 7)
                    //CurrentFrame = 4;
                if (CurrentFrame > 2)
                    CurrentFrame = 0;

                Timer = 0f;
            }
        }

        private void AnimateRight(GameTime gt)
        {
            if (currentKBState != previousKBState)
            {
                //CurrentFrame = 9;
                CurrentFrame = 0;
                YFrame = 2;
            }

            Timer += (float)gt.ElapsedGameTime.TotalMilliseconds;

            if (Timer > Interval)
            {
                CurrentFrame++;

                //if (CurrentFrame > 11)
                   //CurrentFrame = 8;
                if (CurrentFrame > 2)
                    CurrentFrame = 0;

                Timer = 0f;
            }
        }

SourceRect = new Rectangle(CurrentFrame * SpriteWidth, YFrame * SpriteHeight, SpriteWidth, SpriteHeight);

And that’s it. Just use the code that we had from the previous articles, and the animation will now pull from the sprite sheet.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s