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:
- Animation should not be Slower
- Animation should be not be Faster
- Animation should be Smoother
- Animation should load Faster
We will be using following image for the animation:
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) if (FrameTimer > FrameLength) |
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.