# How To Do 2D Animation On Xna : Part 1

Page 1 of 1

## 11 Replies - 66906 Views - Last Post: 22 April 2014 - 01:54 PM

### #1 Hellbroth

Reputation: 17
• Posts: 190
• Joined: 15-August 09

# How To Do 2D Animation On Xna : Part 1

Posted 15 April 2010 - 07:41 PM

Hello everyone again i will try to make a tutorial for 2D sprite animation for Xna.
Things that you will learn in this tutorial will be :

Sprite animation when you are moving your character or when he is standing.

I have tried to do all these things many items and it always confuses me and the basic reason for that
is that most spriteSheets that are there they are not well made.What i mean by that is that most of the times the frames are not in good positions so you can't make a good rectangle box for the animation that
will only include one frame per time and that other times in a line of a spriteSheet different frames have
different sizes so from what you will see i will understand a way of doing this whole animation thing.

Also with this tutorial you will be able to start doing fighting games which i haven't found any
tutorial for.

The Picture that we are going to use :

http://i43.tinypic.com/iyezoz.png

So lets start i will give the code and then i will explain it :

```
Texture2D character;
Vector2 Position = new Vector2(200,200);
Point frameSize = new Point(105,130);
Point currentFrame = new Point (0,2);
Point sheetSize = new Point(12,35);
float speed = 15;

KeyboardState currentState;
KeyboardState theKeyboardState;
KeyboardState oldKeyboardState;

enum State {

Walking,
Punch,
Jump,
JumpForward,
JumpBackgwards

}

State mCurrentState = State.Walking;

TimeSpan nextFrameInterval = TimeSpan.FromSeconds((float)1/ 16);
TimeSpan nextFrame;

```

Ok we did a lot here and i am sorry for that but we are gonna need them all.
First we create a Texture2D to keep the image of our character.
Then we create a Vector2 to hold the Position of our character on the screen.
Now you will notice that i am using Points by using points we are able to change things
all the time fast and easier.In our first point called frameSize the first number holds first the width of the single framewe want to see every time on the screen and the second number holds the height.

Everytime we want to able to see only one frame from the characters spriteSheet that's why
i said single frame.

The point currentFrame holds which position of the spriteSheet we are.
Example :
```Point frameSize = new Point(0,0);

```

This means that we are in the first frame of our spriteSheet in our first line of the spriteSheet.

And last the point sheetSize holds how many frames are on the line and how many lines of frames we have.

I am jumping to states as the rest are pretty common.
We will use the states so we can change from the lines of the spriteSheet more smoothly and also
to be able to do a single line animation.

Next we create the mCurrentState so that the first State we have is when our character is walking.

Last the nextFrameInterval will be used to adjust the animation frame speed so it's not too fast
or to slow.
And the nextFrame to change each time our frame to go to the nextFrame.

We are almost ready to begin only a few things left.Go at the Public Game1() method
and after everything add this :
```TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 100);

```

We are using this to adjust how fast things happen on Xna so the animation speed is not too fast
and we can see it.

Now at our LoadContent method we need to load our picture :

```

```

feilong is the name of the spritesheet i am using if you want to use other spriteSheet you have to
change the name into the name of the spriteSheet you are loading.

Only thing left is how to display only one frame of our character on the screen so let's go to
the draw method :

```
spriteBatch.Begin();
spriteBatch.Draw(character,Position, new Rectangle(
frameSize.X * currentFrame.X,
frameSize.Y * currentFrame.Y,
frameSize.X,
frameSize.Y),
Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
spriteBatch.Draw();

```

What we do here is first we give the name of our Texture2D variable then the Position.
So now we create a Rectangle that will show us on the screen only what's inside this rectangle.

The frameSize.X * currentFrame.X gives the position of our frame each time on X and the
frameSize.Y * currentFrame.Y the position of our frame each time on Y and in the end we give
the frameSize.X for the width of the frame and the frameSize.Y for the height of our frame.

So Now if you press the play button or f5 you should be able to see this :

Isn't this nice?

Well it's there but it doesn't animate so let's do some animation.

Son now when our game starts we want our character to be automaticaly at the standing position
waiting there and animating.Go on the Update method and add this :

```if (mCurrentState == State.Walking)
{

currentFrame.X++;
if (currentFrame.X >= 6)
currentFrame.X = 0;
if (currentFrame.Y >= 2)
{
currentFrame.Y = 2;
characterPosition.Y = 200;
frameSize = new Point(105, 130);
}
}

```

Ok so we have by default the mCurrentState to walking so when the game starts we say
advance the position of our frame by 1 till the frame we are is the 6th.It's only till 6
cause there are only cause this is the number of frames we need to play.
(Keep in mind that the frames are Seven but we start always from 0).
When this happends we put the currentFrame.X at 0 so it can start from the first frame again
and loop all the time.

There is some more code there and you will say why we need that.
I am using the if statement to check if we are in a different line of the spriteSheet to return
back at the standing line.And we do that cause we want when we don't move our character to stay
at the standing position and animating.

Also sometimes a different line has its frames at different heights so we have to adjust it that it
looks that it's always at the ground and not somewhere else.Plus we need to set the frameSizes again
cause if you take for example the line that has the jump animation it's frame has different width's and
heights and we need to change that as we animate and when we finish we have to go back to our original
frameSize.

Now we are standing and Animating so let's see some movement and make something be alive at last.

In our update method before the code we wrote for our standing animation add this :

```currentState = Keyboard.GetState();
theKeyboardState = Keyboard.GetState();

```

And after everything add this :
```oldKeyboardState = theKeyboardState

```

We will use these to get the keyboard input from the user.The theKeyboardState and the oldKeyboardState
will be used later for the single key press.

Now that we can take the input let's move and animate at the same time

Inside the if(mCurrentState == State.Walking){ } and after the standing animation code add this :

```
if (currentState.IsKeyDown(Keys.Right))
{
frameSize = new Point(70, 145);
characterPosition.Y = 190;
currentFrame.Y = 5;
currentFrame.X++;
if (currentFrame.X >= 6)
currentFrame.X = 0;
characterPosition.X += speed;
}

else if (currentState.IsKeyDown(Keys.Left))
{
frameSize = new Point(90, 145);
characterPosition.Y = 180;
currentFrame.Y = 6;
currentFrame.X++;
if (currentFrame.X >= 6)
currentFrame.X = 0;
characterPosition.X -= speed;
}

```

I will explaing only the code for when we press the right key as the code for the left key is the same
only in a different line on the spriteSheet.

So what we do is we change the width and the height of the frame as the frame of the walking right
animation has different width and height then we put the frame on Y position to be at 190
cause otherwise the sprite will be at a different position.

A hint ( What i did to check the positions is i added a new image which was a white line bellow the
feet of the character which is was the ground and i was testing the numbers so that the character will
be always at the same position).

so now the points come handy cause by putting the currentFrame.Y = 6 i change the position of the frame
to go at the line 6 from the line 2 that we were where is the animation for walking right.

Keep in mind that all these happen as long as we pressing the button right that's why we wrote the
code to on the standing animation to return at the line 2 so that our character goes at the animating
position.

At last we use the same code to change between the frames and always return to the 0 frame
so our animation loops and we are adding the speed to our position so we can go right while we
animate.

The number 6 is there to tell that the X frames we need to animate our only 7 as we start from 0
we are still having the spriteSheet point to use later cause some animations need the whole 12-14 animation which the image can hold.

I think we did a lot here and if i continue it will be two much.

Where you can use this :

1).You can use it in fighting games.
3).For flying bullets when your character is shooting
4).Animating buttons,menus and lot's of other things.

In the part 2 you will learn how to do a single key press animation for say a punch and
animation when your character is jumping up,forward and backwards.

Hope you like it guys

This post has been edited by Hellbroth: 17 April 2010 - 10:34 PM

Is This A Good Question/Topic? 1

## Replies To: How To Do 2D Animation On Xna : Part 1

### #2 PsychoCoder

Reputation: 1647
• Posts: 19,853
• Joined: 26-July 07

## Re: How To Do 2D Animation On Xna : Part 1

Posted 15 April 2010 - 08:17 PM

You should have probably submitted this as a tutorial instead of making a thread

### #3 Stuart444

Reputation: 6
• Posts: 55
• Joined: 23-March 07

## Re: How To Do 2D Animation On Xna : Part 1

Posted 16 April 2010 - 01:40 AM

PsychoCoder, on 16 April 2010 - 02:17 AM, said:

You should have probably submitted this as a tutorial instead of making a thread

First of all, I agree with him here ^ Mainly since I usually skim through looking for good tuts I can try every so often in the tutorial section.

Anyway I skimmed over it quickly and it looks like a good tutorial. I'll probably try it out when I get time

### #4 tallic

Reputation: 1
• Posts: 2
• Joined: 07-June 10

## Re: How To Do 2D Animation On Xna : Part 1

Posted 07 June 2010 - 04:34 AM

```spriteBatch.Begin();
spriteBatch.Draw(character,Position, new Rectangle(
frameSize.X * currentFrame.X,
frameSize.Y * currentFrame.Y,
frameSize.X,
frameSize.Y),
Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
spriteBatch.Draw();

```

I'm pretty sure that the last line Should have End() in it??
and also the *.png file should be bigger... im getting like 24 sprite images in this 1 frame.

Thanks for the tutorial it looks cool.

Mod Edit:
Added in code tags. When posting code, please use code tags like below.

### #5 hello1

Reputation: 0
• Posts: 2
• Joined: 08-June 10

## Re: How To Do 2D Animation On Xna : Part 1

Posted 08 June 2010 - 06:01 AM

Where do i paste this section:
```spriteBatch.Begin();
spriteBatch.Draw(character,Position, new Rectangle(
frameSize.X * currentFrame.X,
frameSize.Y * currentFrame.Y,
frameSize.X,
frameSize.Y),
Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
spriteBatch.Draw();

```

Thanks

Mod Edit:
Added in code tags. When posting code, please use code tags like below.

### #6 Stuart444

Reputation: 6
• Posts: 55
• Joined: 23-March 07

## Re: How To Do 2D Animation On Xna : Part 1

Posted 08 June 2010 - 08:46 AM

hello1, on 08 June 2010 - 12:01 PM, said:

Where do i paste this section:
spriteBatch.Begin();
spriteBatch.Draw(character,Position, new Rectangle(
frameSize.X * currentFrame.X,
frameSize.Y * currentFrame.Y,
frameSize.X,
frameSize.Y),
Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
spriteBatch.Draw();

Thanks

In the Draw Method and change the last line to spriteBatch.End();

### #7 Hellbroth

Reputation: 17
• Posts: 190
• Joined: 15-August 09

## Re: How To Do 2D Animation On Xna : Part 1

Posted 09 June 2010 - 07:31 PM

Sorry guys it doesn't let me edit it i don't know why

the right one is

```
spriteBatch.End();

```

And you should put it in the draw method. sorry for this

### #8 tallic

Reputation: 1
• Posts: 2
• Joined: 07-June 10

## Re: How To Do 2D Animation On Xna : Part 1

Posted 11 June 2010 - 01:46 AM

Hi Hellbroth

Could you maybe be so kind to paste your full code again?
and maybe a bigger Spritesheet?

and lastly... Any idea what the code should look like for a combo key press?like doing Down, Forward for a fireball?

Thanks

### #9 Hellbroth

Reputation: 17
• Posts: 190
• Joined: 15-August 09

## Re: How To Do 2D Animation On Xna : Part 1

Posted 11 June 2010 - 02:20 AM

tallic, on 11 June 2010 - 12:46 AM, said:

Hi Hellbroth

Could you maybe be so kind to paste your full code again?
and maybe a bigger Spritesheet?

and lastly... Any idea what the code should look like for a combo key press?like doing Down, Forward for a fireball?

Thanks

For some reason when i was uploading the picture in tha provider it was making it smaler don't know why.
Here is the proper one : http://img812.images...673/feilong.png

Even though i explain everything in order to use other sprite sheets the point is to learn rather than use that specific sprite sheet.

I don't have a full code for that but i explain where you have to put what and why so give it a ready slowly and you will understand it if there is any problem just let me know

Here is a project i did although to see what you can sort of accomplice

### #10 Soyaku

Reputation: 0
• Posts: 47
• Joined: 28-February 08

## Re: How To Do 2D Animation On Xna : Part 1

Posted 27 October 2010 - 12:42 PM

Question: How would one reset the index of currentFrame.X back to 0 during this type of animation? I should be able to figure it out, but I'm still getting used to the game loop concept and have ran into problems. If you don't reset the index back to 0, it will skip frames and make animation with fewer frames show a blink-like effect. (Due to there not being a sprite in said slot.)

Code:
```                //Walk Backward
if (currentState.IsKeyDown(Keys.Left) || currentState2.IsConnected && currentState2.DPad.Left == ButtonState.Pressed)
{
mCurrentState = State.WalkingLeft;

if (mCurrentState == State.WalkingLeft)
{
currentFrame.Y = 5; //This is where Walking Backward is on the sprite sheet
++currentFrame.X; //Increment the column (x) after each loop through update
Position.X -= 10; //Decrement on the x-axis to simulate walking backward
if (currentFrame.X >= 8) //Check to see if the frame count has been exceeded.
{ currentFrame.X = 0; } //Set to beginning of column if character still performing action
}
}

//Crouch
if (currentState.IsKeyDown(Keys.Down) || currentState2.IsConnected && currentState2.DPad.Down == ButtonState.Pressed)
{
mCurrentState = State.Crouching;

if (currentFrame.X != 0) currentFrame.X = 0;
if (mCurrentState == State.Crouching)
{
currentFrame.Y = 3; //This is where the Crouch row is on sprite sheet

if (currentFrame.X < 3) //Crouching is one continuous animation, if it equals the last frame...
{ ++currentFrame.X; }//...increment up to 3 and stop
}

}
```

My crouch only needs to loop to the 3rd frame and stop, but is continuously blinking because of this index problem. Sorry for resurrecting an old topic, figured it'd be better to post a reply than a whole new topic.

Any help is appreciated, thank you!

~Soyaku

This post has been edited by Soyaku: 27 October 2010 - 12:44 PM

Reputation:

## Re: How To Do 2D Animation On Xna : Part 1

Posted 07 December 2010 - 02:20 PM

Sorry about the last post. IE had the page all screwy, so it posted wihtout me doing anything but entering in the Captcha...

The two ways I have seen 2D animations are:
• Sprite sheet.
• Separate image file for each frame and iterating through the collection of images when drawing a frame.

I would assume that the way you are demonstrating is "better" since you would have less items in memory (even if it is the same amount of memory being used). Have you ever tried the second option? If so, did you ever run into issues by doing it that way?

### #12 Hellbroth

Reputation: 17
• Posts: 190
• Joined: 15-August 09

## Re: How To Do 2D Animation On Xna : Part 1

Posted 22 April 2014 - 01:54 PM

Soyaku, on 27 October 2010 - 01:42 PM, said:

Question: How would one reset the index of currentFrame.X back to 0 during this type of animation? I should be able to figure it out, but I'm still getting used to the game loop concept and have ran into problems. If you don't reset the index back to 0, it will skip frames and make animation with fewer frames show a blink-like effect. (Due to there not being a sprite in said slot.)

Code:
```                //Walk Backward
if (currentState.IsKeyDown(Keys.Left) || currentState2.IsConnected && currentState2.DPad.Left == ButtonState.Pressed)
{
mCurrentState = State.WalkingLeft;

if (mCurrentState == State.WalkingLeft)
{
currentFrame.Y = 5; //This is where Walking Backward is on the sprite sheet
++currentFrame.X; //Increment the column (x) after each loop through update
Position.X -= 10; //Decrement on the x-axis to simulate walking backward
if (currentFrame.X >= 8) //Check to see if the frame count has been exceeded.
{ currentFrame.X = 0; } //Set to beginning of column if character still performing action
}
}

//Crouch
if (currentState.IsKeyDown(Keys.Down) || currentState2.IsConnected && currentState2.DPad.Down == ButtonState.Pressed)
{
mCurrentState = State.Crouching;

if (currentFrame.X != 0) currentFrame.X = 0;
if (mCurrentState == State.Crouching)
{
currentFrame.Y = 3; //This is where the Crouch row is on sprite sheet

if (currentFrame.X < 3) //Crouching is one continuous animation, if it equals the last frame...
{ ++currentFrame.X; }//...increment up to 3 and stop
}

}
```

My crouch only needs to loop to the 3rd frame and stop, but is continuously blinking because of this index problem. Sorry for resurrecting an old topic, figured it'd be better to post a reply than a whole new topic.

Any help is appreciated, thank you!

~Soyaku

Hello

```

currentFrame.X = 0;

```