Almost every game needs objects that move and change their appearance. And one of the most common tasks is not supported by default in XNA, so I had to design my own mechanisms to deal with 2D animations.
If you plan on playing with the 2D animations, you have to know 2 simple terms:
- Sprite – a 2D graphic object that is placed on the screen.
- Sprite sheet – a set of 2D graphics objects placed in one file in order to limit file access operations and logic division of the outer assets.
Basically the AnimatingSprite object takes sprite sheet, divides it into animations and plays the pictures in order, creating illusion of a moving picture.
The crucial thing for the AnimatingSprite class is preparation of the sprite sheet. The distance between pictures next to each other has to be the same both horizontally and vertically.
Example sprite sheet
Some elements of this package are found in the Internet, most of them are upgraded by me:
Example of use (Initializing animation in XNA 4.0)
AnimatingSprite hitAnim = new AnimatingSprite(); hitAnim.Texture = Texture2D.FromStream(device, File.OpenRead("your_animation.png")); hitAnim.Animations.Add("animation_name", new Animation(320, 84, 5, 0, 0)); hitAnim.CurrentAnimation = "animation_name"; hitAnim.isRepeatable = false; hitAnim.Animations["animation_name"].FramesPerSecond = 10; hitAnim.Position = new Vector2(500, 500);
Texture field is a spritesheet read from file.
Animations field is a dictionary where animations are stored and can be called by name.
Animation class helps to divide spritesheet to separate pictures. The constructor of this class has 5 arguments:
- 1: Width of the spritesheet
- 2: Height if the spritesheet
- 3: Number of frames
- 4: Beginning of the picture in pixels counting from left
- 5: Beginning of the picture in pixels counting from top
CurrentAnimation field sets the animation that needs to be displayed.
isRepeatable field indicates if animation should be looped or it should be played only once.
FramesPerSecond field gets or sets the speed of the specific animation.
Position field gets or sets the screen positioning of the picture currently shown.
Example of use
hitAnim.StartAnimation(); // Starts the animation hitAnim.StopAnimation(); // Stops the animation hitAnim.Draw(spriteBatch); // Draws the animation (put it in the Draw method) hitAnim.Update(gameTime); // Updates the animation (put it in the Update method)