AnimationManager.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Tutorial020.Models;
  9. namespace Tutorial020.Managers
  10. {
  11. public class AnimationManager : ICloneable
  12. {
  13. private Animation _animation;
  14. private float _timer;
  15. public Animation CurrentAnimation
  16. {
  17. get
  18. {
  19. return _animation;
  20. }
  21. }
  22. public float Layer { get; set; }
  23. public Vector2 Origin { get; set; }
  24. public Vector2 Position { get; set; }
  25. public float Rotation { get; set; }
  26. public float Scale { get; set; }
  27. public AnimationManager(Animation animation)
  28. {
  29. _animation = animation;
  30. Scale = 1f;
  31. }
  32. public void Draw(SpriteBatch spriteBatch)
  33. {
  34. spriteBatch.Draw(
  35. _animation.Texture,
  36. Position,
  37. new Rectangle(
  38. _animation.CurrentFrame * _animation.FrameWidth,
  39. 0,
  40. _animation.FrameWidth,
  41. _animation.FrameHeight
  42. ),
  43. Color.White,
  44. Rotation,
  45. Origin,
  46. Scale,
  47. SpriteEffects.None,
  48. Layer
  49. );
  50. }
  51. public void Play(Animation animation)
  52. {
  53. if (_animation == animation)
  54. return;
  55. _animation = animation;
  56. _animation.CurrentFrame = 0;
  57. _timer = 0;
  58. }
  59. public void Stop()
  60. {
  61. _timer = 0f;
  62. _animation.CurrentFrame = 0;
  63. }
  64. public void Update(GameTime gameTime)
  65. {
  66. _timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
  67. if(_timer > _animation.FrameSpeed)
  68. {
  69. _timer = 0f;
  70. _animation.CurrentFrame++;
  71. if (_animation.CurrentFrame >= _animation.FrameCount)
  72. _animation.CurrentFrame = 0;
  73. }
  74. }
  75. public object Clone()
  76. {
  77. var animationManager = this.MemberwiseClone() as AnimationManager;
  78. animationManager._animation = animationManager._animation.Clone() as Animation;
  79. return animationManager;
  80. }
  81. }
  82. }