// Copyright (c) Craftwork Games. All rights reserved. // Licensed under the MIT license. // See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using MonoGame.Extended.Animations; namespace MonoGame.Extended.Graphics; /// /// Represents an animated sprite that can play, pause, and update animations. /// public class AnimatedSprite : Sprite { private readonly SpriteSheet _spriteSheet; private IAnimation _animation; private readonly Texture2DRegion[] _regions; /// /// Gets the animation controller used to control the current animation of this animated sprite. /// public IAnimationController Controller { get; private set; } /// /// Gets the name of the current animation playing. /// public string CurrentAnimation => _animation.Name; /// /// Initializes a new instance of the class with the specified /// . /// /// The that contains the animations. public AnimatedSprite(SpriteSheet spriteSheet) : base(spriteSheet.TextureAtlas[0]) { ArgumentNullException.ThrowIfNull(spriteSheet); _spriteSheet = spriteSheet; } /// /// Initializes a new instance of the class with the specified /// . /// /// The that contains the animations. /// The initial animation to play public AnimatedSprite(SpriteSheet spriteSheet, string initialAnimation) :this(spriteSheet) { _animation = spriteSheet.GetAnimation(initialAnimation); Controller = new AnimationController(_animation); TextureRegion = _spriteSheet.TextureAtlas[Controller.CurrentFrame]; } /// /// Sets the animation to use for this animated sprite. /// /// The name of the animation. /// The of the animation. /// /// Thrown if the source spritesheet does not contain an animation a name that matches the parameter. /// public IAnimationController SetAnimation(string name) { _animation = _spriteSheet.GetAnimation(name); Controller = new AnimationController(_animation); TextureRegion = _spriteSheet.TextureAtlas[Controller.CurrentFrame]; return Controller; } /// public void Update(GameTime gameTime) { Update(gameTime.ElapsedGameTime); } /// public void Update(TimeSpan elapsedTime) { int index = Controller.CurrentFrame; Controller.Update(elapsedTime); // If the current frame changed during the update, change the texture region if (index != Controller.CurrentFrame) { TextureRegion = _spriteSheet.TextureAtlas[Controller.CurrentFrame]; } } }