For all the programmers using MonoGame: here is an example how to create sprite animations.
The only external content you need is a spritesheet.
Create a new class with the name SpriteManager.cs and put following code in it:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Animation
{
public class SpriteManager
{
protected Texture2D Texture;
public Vector2 Position = Vector2.Zero;
public Color Color = Color.White;
public Vector2 Origin;
public float Rotation = 0f;
public float Scale = 1f;
public SpriteEffects SpriteEffect;
protected Rectangle[] Rectangles;
protected int FrameIndex = 0;
public SpriteManager(Texture2D Texture, int frames)
{
this.Texture = Texture;
int width = Texture.Width / frames;
Rectangles = new Rectangle[frames];
for (int i = 0; i < frames; i++)
Rectangles[i] = new Rectangle(i * width, 0, width, Texture.Height);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, Rectangles[FrameIndex], Color, Rotation, Origin, Scale, SpriteEffect, 0f);
}
}
}
This code divides the spritesheet into frames, which are later drawn on the screen.
Create a new class with the name SpriteAnimation.cs and put following code in it:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Animation
{
public class SpriteAnimation : SpriteManager
{
private float timeElapsed;
public bool IsLooping = false;
private float timeToUpdate; //default, you may have to change it
public int FramesPerSecond { set { timeToUpdate = (1f / value);
public SpriteAnimation(Texture2D Texture, int frames) : base(Texture, frames) { }
public void Update(GameTime gameTime)
{
timeElapsed += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (timeElapsed > timeToUpdate)
{
timeElapsed -= timeToUpdate;
if (FrameIndex < Rectangles.Lenght - 1)
FrameIndex++;
else if (IsLooping)
FrameIndex = 0;
}
}
}
}
This class creates the animation.
Now you have to import a spritesheet image file via the MonoGame Pipeline. In my case it is named "file.png".
This is how you use the classes in Game1.cs; simply add following code to the existing code:
SpriteAnimation animation; //outside all methods
animation = new SpriteAnimation(Content.Load<Texture2D>("file");
animation.IsLooping = true;
animation.FramesPerSecond = 5;
animation.Position = new Vector2(100, 100);
//add this to the method LoadContent()
animation.Update(gameTime); //add this to Update()
spriteBatch.Begin();
animation.Draw(spriteBatch);
spriteBatch.End();
//add this to method Draw(GameTime gameTime)
Have fun with your animations.