Sprite.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using Microsoft.Xna.Framework;
  4. using Microsoft.Xna.Framework.Graphics;
  5. namespace RockRain.Core
  6. {
  7. /// <summary>
  8. /// This is a game component that implements a Animated Sprite.
  9. /// </summary>
  10. public class Sprite : DrawableGameComponent
  11. {
  12. private int activeFrame;
  13. private readonly Texture2D texture;
  14. private List<Rectangle> frames;
  15. protected Vector2 position;
  16. protected TimeSpan elapsedTime = TimeSpan.Zero;
  17. protected Rectangle currentFrame;
  18. protected long frameDelay;
  19. protected SpriteBatch sbBatch;
  20. /// <summary>
  21. /// Default construtor
  22. /// </summary>
  23. /// <param name="game">The game object</param>
  24. /// <param name="theTexture">Texture that contains the sprite frames</param>
  25. public Sprite(Game game, ref Texture2D theTexture)
  26. : base(game)
  27. {
  28. texture = theTexture;
  29. activeFrame = 0;
  30. }
  31. /// <summary>
  32. /// List with the frames of the animation
  33. /// </summary>
  34. public List<Rectangle> Frames
  35. {
  36. get { return frames; }
  37. set { frames = value; }
  38. }
  39. /// <summary>
  40. /// Allows the game component to perform any initialization it needs to
  41. /// before starting to run. This is where it can query for any required
  42. /// services and load content.
  43. /// </summary>
  44. public override void Initialize()
  45. {
  46. // Get the current spritebatch
  47. sbBatch = (SpriteBatch) Game.Services.GetService(typeof (SpriteBatch));
  48. base.Initialize();
  49. }
  50. /// <summary>
  51. /// Allows the game component to update itself.
  52. /// </summary>
  53. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  54. public override void Update(GameTime gameTime)
  55. {
  56. elapsedTime += gameTime.ElapsedGameTime;
  57. // it's time to a next frame?
  58. if (elapsedTime > TimeSpan.FromMilliseconds(frameDelay))
  59. {
  60. elapsedTime -= TimeSpan.FromMilliseconds(frameDelay);
  61. activeFrame++;
  62. if (activeFrame == frames.Count)
  63. {
  64. activeFrame = 0;
  65. }
  66. // Get the current frame
  67. currentFrame = frames[activeFrame];
  68. }
  69. base.Update(gameTime);
  70. }
  71. /// <summary>
  72. /// Draw the sprite.
  73. /// </summary>
  74. /// <param name="gameTime">Provides a snapshot of timing values.</param>
  75. public override void Draw(GameTime gameTime)
  76. {
  77. sbBatch.Draw(texture, position, currentFrame, Color.White);
  78. base.Draw(gameTime);
  79. }
  80. }
  81. }