using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace WindowsGame1
{
class AnimatedSprite : EntitySprite
{
private Rectangle[] m_Frames;
private int m_CurrentFrame = 0;
private float m_Timer = 0f;
private float m_FrameLength = 1f/5f;
private bool m_Run = true;
///
/// The frames per second of the animation;
///
public int FramesPerSecond
{
get { return (int)(1f / m_FrameLength); }
set { m_FrameLength = 1f / (float)value; }
}
///
/// The current frame in the animation.
///
public Rectangle CurrentFrame
{
get { return m_Frames[m_CurrentFrame]; }
}
///
/// Constructor: Automatically generates the source rectangles from the sprite sheet texture.
///
/// The game that this component is associated with.
/// The Texture to use as a sprite sheet.
/// The position on the screen to draw the animated sprite.
/// The size of an individual frame in the sprite sheet.
/// The total number of frames in the sprite sheet.
public AnimatedSprite(Game p_Game, Texture2D p_SpriteSheet, Vector2 p_Position, Vector2 p_FrameSize, int p_NumFrames)
: base(p_Game, p_SpriteSheet, p_Position)
{
m_Frames = new Rectangle[p_NumFrames];
Vector2 curFramePos = Vector2.Zero;
int frameCount = 0;
while (curFramePos.Y < p_SpriteSheet.Height && frameCount < p_NumFrames)
{
while (curFramePos.X < p_SpriteSheet.Width && frameCount < p_NumFrames)
{
m_Frames[frameCount] = new Rectangle((int)curFramePos.X, (int)curFramePos.Y, (int)p_FrameSize.X, (int)p_FrameSize.Y);
curFramePos.X += p_FrameSize.X;
frameCount++;
}
curFramePos.Y += p_FrameSize.Y;
curFramePos.X = 0;
}
}
///
/// The update method called by XNA during it's update cycle.
///
/// The game time object passed in by XNA.
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (m_Run)
{
m_Timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (m_Timer >= m_FrameLength)
{
m_Timer = 0f;
m_CurrentFrame = (m_CurrentFrame + 1) % m_Frames.Length;
}
}
}
///
/// Reset the animation from the beginning.
///
public void Reset()
{
m_CurrentFrame = 0;
m_Timer = 0f;
}
///
/// The Draw method called by XNA during it's draw cycle.
///
/// The game time object passed in by XNA.
public override void Draw(GameTime gameTime)
{
m_SpriteBatch.Begin();
m_SpriteBatch.Draw(m_Texture, m_Position, m_Frames[m_CurrentFrame], m_Color, m_Rotation, m_RotationOrigin, m_Scale, SpriteEffects.None, m_LayerDepth);
m_SpriteBatch.End();
}
///
/// Used to turn animation on and off.
///
/// Bool representing whether animation is running or not.
public void Animate(bool p_Run)
{
m_Run = p_Run;
}
}
}