Sprite.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Microsoft.Xna.Framework.Graphics; // for Texture2D
  5. using Microsoft.Xna.Framework; // for Vector2
  6. namespace Microsoft.Xna.Samples.GameComponents
  7. {
  8. class Sprite : DrawableGameComponent
  9. {
  10. private readonly Texture2D texture; // sprite texture
  11. private Vector2 position; // sprite position on screen
  12. private Vector2 speed; // speed in pixels
  13. private readonly SpriteBatch spriteBatch;
  14. public Sprite(Game game, Texture2D Texture, Vector2 Position, Vector2 Speed, SpriteBatch spriteBatch)
  15. : base(game)
  16. {
  17. this.texture = Texture;
  18. this.position = Position;
  19. this.spriteBatch = spriteBatch;
  20. this.speed = Speed;
  21. }
  22. public override void Update(GameTime gameTime)
  23. {
  24. // Keep inside the screen
  25. // right
  26. if(position.X + texture.Width + speed.X > Game.Window.ClientBounds.Width)
  27. speed.X = -speed.X;
  28. // bottom
  29. if (position.Y + texture.Height + speed.Y > Game.Window.ClientBounds.Height)
  30. speed.Y = -speed.Y;
  31. // left
  32. if (position.X + speed.X < 0)
  33. speed.X = -speed.X;
  34. // top
  35. if (position.Y + speed.Y < 0)
  36. speed.Y = -speed.Y;
  37. // update position
  38. position += speed;
  39. }
  40. public override void Draw(GameTime gameTime)
  41. {
  42. spriteBatch.Draw(texture, position, Color.White);
  43. }
  44. }
  45. }