Player.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 Tutorial009.Sprites
  10. {
  11. public class Player : Sprite
  12. {
  13. public Player(Texture2D texture)
  14. : base(texture)
  15. {
  16. }
  17. public override void Update(GameTime gameTime, List<Sprite> sprites)
  18. {
  19. Move();
  20. foreach (var sprite in sprites)
  21. {
  22. if (sprite == this)
  23. continue;
  24. if ((this.Velocity.X > 0 && this.IsTouchingLeft(sprite)) ||
  25. (this.Velocity.X < 0 & this.IsTouchingRight(sprite)))
  26. this.Velocity.X = 0;
  27. if ((this.Velocity.Y > 0 && this.IsTouchingTop(sprite)) ||
  28. (this.Velocity.Y < 0 & this.IsTouchingBottom(sprite)))
  29. this.Velocity.Y = 0;
  30. }
  31. Position += Velocity;
  32. Velocity = Vector2.Zero;
  33. }
  34. private void Move()
  35. {
  36. if (Keyboard.GetState().IsKeyDown(Input.Left))
  37. Velocity.X = -Speed;
  38. else if (Keyboard.GetState().IsKeyDown(Input.Right))
  39. Velocity.X = Speed;
  40. if (Keyboard.GetState().IsKeyDown(Input.Up))
  41. Velocity.Y = -Speed;
  42. else if (Keyboard.GetState().IsKeyDown(Input.Down))
  43. Velocity.Y = Speed;
  44. }
  45. }
  46. }