Sgt. Conker We are "absolutely fine"

15Nov/090

Article : Simple 2D Animated Sprite

by Casey Young

This article describes how to animate a 2D sprite sheet with XNA.

I have decided to break this article into seperate pages, starting with the basics, and then progressing towards making a simple animated sprite class.

This first part is a basic tutorial on how to make a simple animated sprite using a set of images. There are better ways to animate sprites, but this will get you the basics on how it is accomplished, so the code is simple, and not optimized.

First start off with creating a new XNA 3.1 project.

newProject

With this newly created project, we want to add the images that we want to animate.
Click here for the images to use. Add those to the project's content folder.

Next we want to add a few private variables to the Game1.cs file.

public class Game1 : Microsoft.Xna.Framework.Game
	{
		GraphicsDeviceManager graphics;
		SpriteBatch spriteBatch;

		private List scribbles;  // a list of the textures we are going to animate
		private Vector2 scribbleOrigin;  // the center of the sprite
		private Vector2 scribblePos; // where to draw the sprite
		private int frameCount;  // how many frames are there to animate
		private float timePerFrame; // how long to display each frame
		private float totalElapsed;  // how long has it elapsed.
		private int currentFrame;  // what frame are we on
		private int framesPerSec; // how many frames of animation do we want to show per second.
...

This will get all the variables to animate the textures to make a nice animated sprite. Next you want to load up the textures, and set the variables with their default values. You want to do that in LoadContent in Game1.cs.

		protected override void LoadContent()
		{
			// Create a new SpriteBatch, which can be used to draw textures.
			spriteBatch = new SpriteBatch(GraphicsDevice);

			// init the list
			scribbles = new List();
			// loop thru all the textures, and add them to the list
			for (int i = 1; i <= 10; i++)
			{
				if(i < 10)
					scribbles.Add(Content.Load("scribble0" + i));
				else
					scribbles.Add(Content.Load("scribble" + i));
			}
			// set the number of frames to the size of the List
			frameCount = scribbles.Count;
			// how many frames do we want to show a sec?  15 looked like a good number
			framesPerSec = 15;
			// compute how long it we should show each frame
			timePerFrame = (float) 1/framesPerSec;
			// we want to start from the first frame
			currentFrame = 0;
			// just started, so elapse is 0
			totalElapsed = 0;
			// get the middle of the first texture (each texture is teh same size, so we can use the first one only)
			scribbleOrigin = new Vector2(scribbles[0].Width / 2, scribbles[0].Height / 2);
			// get the center of the current display
			scribblePos = new Vector2(graphics.PreferredBackBufferWidth/2, graphics.PreferredBackBufferHeight/2);
		}

With all the variables setup and the textures loaded, lets get the logic in to start animating the sprite. To do this, we want to add the following code to the Update function in Game1.cs so it looks like the following:

		protected override void Update(GameTime gameTime)
		{
			// Allows the game to exit
			if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
				this.Exit();

			float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
			totalElapsed += elapsed;

			if (totalElapsed > timePerFrame)
			{
				currentFrame++;
				// we want to keep the current frame betwee 0 and frameCount -1
				currentFrame = currentFrame % frameCount;
				// reset the total elapsed time.
				totalElapsed -= timePerFrame;
			}

			base.Update(gameTime);
		}

We are almost done here. Only thing that is left is to draw the sprite. To do this, we want to add the following code to the Draw function in Game1.cs.

protected override void Draw(GameTime gameTime)
		{
			GraphicsDevice.Clear(Color.CornflowerBlue);

			spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred,
							  SaveStateMode.SaveState);

			spriteBatch.Draw(scribbles[currentFrame], scribblePos, null, Color.White, 0,
				scribbleOrigin, 1.0f, SpriteEffects.None, 0.6f);

			spriteBatch.End();

			base.Draw(gameTime);
		}

Once you add that, compile the project and run it. You should see a big scribble animating on the center of your screen.

To download the full project for this part of the article with images and source code, click here.

Up on the next page, we will merge the images into a sprite sheet, and do the animation with just 1 texture!

About ElementCy

Private Slaq0r
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.