public void Play() => IsPlaying = true; public void Pause() => IsPlaying = false; public void Stop() { IsPlaying = false; _currentFrame = 0; _elapsedTime = 0; } public void Restart() { _currentFrame = 0; _elapsedTime = 0; IsPlaying = true; } } using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; public class Game1 : Game { private GraphicsDeviceManager _graphics; private SpriteBatch _spriteBatch; private AnimatedSprite _animatedSprite; private Texture2D _spritesheet;
_elapsedTime += gameTime.ElapsedGameTime.TotalSeconds; monogame animated sprite
public AnimatedSprite(Texture2D texture, int frameWidth, int frameHeight, double framesPerSecond, bool looping = true) { _texture = texture; _frames = new List<Rectangle>(); _currentFrame = 0; _timePerFrame = 1.0 / framesPerSecond; _elapsedTime = 0; _looping = looping; IsPlaying = true; public void Play() => IsPlaying = true; public
if (_elapsedTime >= _timePerFrame) { _currentFrame++; _elapsedTime -= _timePerFrame; public void Play() =>
// Example controls var kstate = Keyboard.GetState(); if (kstate.IsKeyDown(Keys.Space) && !_animatedSprite.IsPlaying) _animatedSprite.Play(); if (kstate.IsKeyDown(Keys.P)) _animatedSprite.Pause(); if (kstate.IsKeyDown(Keys.R)) _animatedSprite.Restart();
public void Draw(SpriteBatch spriteBatch, Vector2 position, SpriteEffects effects = SpriteEffects.None) { spriteBatch.Draw(_texture, position, _frames[_currentFrame], Color.White, 0f, Vector2.Zero, 1f, effects, 0f); }
Here’s a self-contained, ready-to-use piece for .