using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace CarFire { public class AnimatedTexture { private int framecount; private Texture2D myTexture; private float TimePerFrame; private int Frame, Row; private float TotalElapsed; private bool Paused, loop; public float Rotation, Scale, Depth; public Vector2 Origin; //rotation is pretty much always zero, scale determines size, depth is 0.5f public AnimatedTexture(Vector2 Origin, float Rotation, float Scale, float Depth) { this.Origin = Origin; this.Rotation = Rotation; this.Scale = Scale; this.Depth = Depth; } //asset is the file name w/o the extension, framecount is the # of frames per row, framespersec determines speed of the animation //loop will determine if the animation repeats, row chooses which row of the animation to play starting with 0 public void Load(GraphicsDevice device, ContentManager content, string asset, int FrameCount, int FramesPerSec, bool Loop, int row) { framecount = FrameCount; myTexture = content.Load(asset); TimePerFrame = (float)1 / FramesPerSec; Frame = 0; TotalElapsed = 0; Paused = false; loop = Loop; Row = row; } // class AnimatedTexture public void UpdateFrame(TimeSpan timeSpan) { float elapsed = timeSpan.Milliseconds; if (Paused) return; TotalElapsed += elapsed; if (TotalElapsed > TimePerFrame) { Frame++; // Keep the Frame between 0 and the total frames, minus one. if (framecount != 0) Frame = Frame % framecount; else Console.WriteLine("AHHH!"); TotalElapsed -= TimePerFrame; } //If loop is false and the current Frame is the last frame //then stop playing the animation if ((Frame == framecount - 1) && loop == false) Pause(); } // class AnimatedTexture public void DrawFrame(SpriteBatch Batch, Vector2 screenpos) { DrawFrame(Batch, Frame, screenpos); } public void DrawFrame(SpriteBatch Batch, int frame, Vector2 screenpos) { int FrameWidth = myTexture.Width / framecount; Rectangle sourcerect = new Rectangle(FrameWidth * Frame, Row * 64, FrameWidth, 64); Console.WriteLine(Frame); Batch.Draw(myTexture, screenpos, sourcerect, Color.White, Rotation, Origin, Scale, SpriteEffects.None, Depth); } public bool IsPaused { get { return Paused; } } public void Reset() { Frame = 0; TotalElapsed = 0f; } public void Stop() { Pause(); Reset(); } public void Play() { Paused = false; } public void Pause() { Paused = true; } } }