// Split texture into frames (assumes frames in a single row) int columns = texture.Width / frameWidth; for (int i = 0; i < columns; i++) { _frames.Add(new Rectangle(i * frameWidth, 0, frameWidth, frameHeight)); } }
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;
if (_elapsedTime >= _timePerFrame) { _currentFrame++; _elapsedTime -= _timePerFrame; monogame animated sprite
public void Update(GameTime gameTime) { if (!IsPlaying) return;
if (_currentFrame >= _frames.Count) { if (_looping) _currentFrame = 0; else { _currentFrame = _frames.Count - 1; IsPlaying = false; } } } } // Split texture into frames (assumes frames in
Here’s a self-contained, ready-to-use piece for .
_animatedSprite.Update(gameTime); base.Update(gameTime); } for (int i = 0
// 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();