Sprite.cs 2.9 KB

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