Player.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.Xna.Framework;
  7. using Microsoft.Xna.Framework.Graphics;
  8. using Microsoft.Xna.Framework.Input;
  9. namespace Tutorial007.Sprites
  10. {
  11. public class Player : Sprite
  12. {
  13. public bool HasDied = false;
  14. public Player(Texture2D texture)
  15. : base(texture)
  16. {
  17. }
  18. public override void Update(GameTime gameTime, List<Sprite> sprites)
  19. {
  20. Move();
  21. foreach(var sprite in sprites)
  22. {
  23. if (sprite == this)
  24. continue;
  25. if(sprite.Rectangle.Intersects(this.Rectangle))
  26. {
  27. this.HasDied = true;
  28. }
  29. }
  30. Position += Velocity;
  31. // Keep the sprite on the screen
  32. Position.X = MathHelper.Clamp(Position.X, 0, Game1.ScreenWidth - Rectangle.Width);
  33. // Resest the velocity for when the user isn't holding down a key
  34. Velocity = Vector2.Zero;
  35. }
  36. private void Move()
  37. {
  38. if (Input == null)
  39. throw new Exception("Please assign a value to 'Input'");
  40. if (Keyboard.GetState().IsKeyDown(Input.Left))
  41. Velocity.X = -Speed;
  42. else if (Keyboard.GetState().IsKeyDown(Input.Right))
  43. Velocity.X = Speed;
  44. }
  45. }
  46. }