using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace BouncyCatIsBouncy { class Animation : IDrawable, IUpdateable { SpriteBatch m_batch; Texture2D m_sheet; int m_cellWidth, m_cellHeight; int m_xCell, m_yCell; float m_timeBeforeFlip; public float Speed { get; set; } public float Rotation { get; set; } public Vector2 Center { get; set; } public int Width { get; set; } public int Height { get; set; } public bool Animating { get; set; } public int Padding { get; set; } public bool StopAtEnd { get; set; } public Animation(SpriteBatch batch, Texture2D sheet, int cellWidth, int cellHeight) { m_timeBeforeFlip = Speed = 100f; m_batch = batch; m_sheet = sheet; Width = m_cellWidth = cellWidth; Height = m_cellHeight = cellHeight; } public void Update(float dt) { if (!Animating) return; m_timeBeforeFlip -= dt; if (m_timeBeforeFlip < 0.0f) { m_timeBeforeFlip += Speed; m_xCell++; if (m_xCell * (m_cellWidth + Padding) >= m_sheet.Width) { m_xCell = 0; m_yCell++; if (m_yCell * (m_cellHeight + Padding) >= m_sheet.Height) { m_yCell = 0; Animating = !StopAtEnd; } } } } public void Draw() { m_batch.Draw(m_sheet, new Rectangle((int)Center.X, (int)Center.Y, Width, Height), new Rectangle(m_xCell * (m_cellWidth + Padding), m_yCell * (m_cellHeight + Padding), m_cellWidth + Padding, m_cellHeight + Padding), Color.White, Rotation, new Vector2(m_cellWidth / 2, m_cellHeight / 2), SpriteEffects.None, 1.0f); } } }