Sunday, January 9, 2011

XNA Game Development Tips and Tricks 5: Animate 2D Sprites

Animation is very important part of game development, if your game does not have any kind of animation it will look very dull.

While doing animation we have to consider many aspects of the game:

  1. Animation should not be Slower
  2. Animation should be not be Faster
  3. Animation should be Smoother
  4. Animation should load Faster

We will be using following image for the animation:

256x32

If you look at above image, it is single image and not 8 tanks. Reason why we are not having 8 different images and loading them in the game is because it will take more time compared to having single long image loaded. If you have just one single sprite in your game for animation it will not make any difference, but if you have many sprites to be animated you will see significant performance difference. So let us see how we can animate the sprite and how we can control frame rates for the sprite.

First we will declare all required variables to be use.

private int FrameCount = 8; //number of frames in image
private int CurrentFrame = 0; //current frame to display
private float FrameLength = 0.12f; //Frame length per frame.. calculated 1/8 i.e. one second divided by number of frames (8)
private float FrameTimer = 0.0f; //Keep note of time

Now let’s load the content in memory, and add image to the Content project.

mSpriteTexture = Content.Load<Texture2D>(“bluetank”);

now, lets write Update code, which will update the current frame number which we would want to show to the user. Code which we have written in Update method will render 8 Frames in a second.

public void Update(GameTime gameTime)
        {
            FrameTimer += (float)gameTime.ElapsedGameTime.TotalSeconds; //Find out the CurrentTimer and based on this we will calculate which Frame to render.

            if (FrameTimer > FrameLength)
            {
                FrameTimer = 0.0f; //Reset FrameTimer to 0
                CurrentFrame = (CurrentFrame + 1) % FrameCount;  //Set CurrentFrame
            }
        }

Finally draw the sprite on the screen with the updated Frame.

theSpriteBatch.Draw(mSpriteTexture, Position, new Rectangle(CurrentFrame * 26, 0, 26, mSpriteTexture.Height), Color.White);

Once you write above code, build it, run it and you should be able to see Your Sprite Animating.

No comments:

Post a Comment