AnimationManager.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 Tutorial030.Models;
  9. namespace Tutorial030.Managers
  10. {
  11. public class AnimationManager
  12. {
  13. private Animation _animation;
  14. private float _timer;
  15. private bool _updated;
  16. public int FrameWidth
  17. {
  18. get
  19. {
  20. return _animation.FrameWidth;
  21. }
  22. }
  23. public int FrameHeight
  24. {
  25. get
  26. {
  27. return _animation.FrameHeight;
  28. }
  29. }
  30. public Vector2 Position { get; set; }
  31. public float Layer { get; set; }
  32. public AnimationManager(Animation animation)
  33. {
  34. _animation = animation;
  35. }
  36. public void Draw(SpriteBatch spriteBatch)
  37. {
  38. if (!_updated)
  39. throw new Exception("Need to call 'Update' first");
  40. _updated = false;
  41. spriteBatch.Draw(_animation.Texture,
  42. Position,
  43. new Rectangle(_animation.CurrentFrame * _animation.FrameWidth,
  44. 0,
  45. _animation.FrameWidth,
  46. _animation.FrameHeight),
  47. Color.White,
  48. 0f,
  49. new Vector2(0, 0),
  50. 1f,
  51. SpriteEffects.None,
  52. Layer);
  53. }
  54. public void Play(Animation animation)
  55. {
  56. if (_animation == animation)
  57. return;
  58. _animation = animation;
  59. _animation.CurrentFrame = 0;
  60. _timer = 0;
  61. }
  62. public void Stop()
  63. {
  64. _timer = 0f;
  65. _animation.CurrentFrame = 0;
  66. }
  67. public void Update(GameTime gameTime)
  68. {
  69. _updated = true;
  70. _timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
  71. if (_timer > _animation.FrameSpeed)
  72. {
  73. _timer = 0f;
  74. _animation.CurrentFrame++;
  75. if (_animation.CurrentFrame >= _animation.FrameCount)
  76. _animation.CurrentFrame = 0;
  77. }
  78. }
  79. }
  80. }