Player.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 Tutorial021.Sprites
  10. {
  11. public class Player : Sprite
  12. {
  13. private bool _onGround;
  14. private bool _jumping;
  15. public Player(Texture2D texture)
  16. : base(texture)
  17. {
  18. }
  19. public override void Update(GameTime gameTime)
  20. {
  21. if (Keyboard.GetState().IsKeyDown(Keys.A))
  22. _velocity.X = -2f;
  23. else if (Keyboard.GetState().IsKeyDown(Keys.D))
  24. _velocity.X = 2f;
  25. else _velocity.X = 0f;
  26. if (Keyboard.GetState().IsKeyDown(Keys.Space))
  27. _jumping = true;
  28. }
  29. public override void OnCollide(Sprite sprite)
  30. {
  31. var test = sprite.Centre - (this.Centre);
  32. var onTop = this.WillIntersectTop(sprite);
  33. var onLeft = this.WillIntersectLeft(sprite);
  34. var onRight = this.WillIntersectRight(sprite);
  35. var onBotton = this.WillIntersectBottom(sprite);
  36. if (onTop)
  37. {
  38. _onGround = true;
  39. _velocity.Y = sprite.Rectangle.Top - this.Rectangle.Bottom;
  40. //this.Position = new Vector2(this.Position.X, sprite.Rectangle.Top - this.Origin.Y);
  41. //this._velocity.Y = 0;
  42. }
  43. else if (onLeft && _velocity.X > 0)
  44. {
  45. _velocity.X = 0;
  46. }
  47. else if (onRight && _velocity.X < 0)
  48. {
  49. _velocity.X = 0;
  50. }
  51. else if (onBotton)
  52. {
  53. _velocity.Y = 1;
  54. }
  55. }
  56. public override void ApplyPhysics(GameTime gameTime)
  57. {
  58. if (!_onGround)
  59. _velocity.Y += 0.2f;
  60. if (_onGround && _jumping)
  61. {
  62. _velocity.Y = -5f;
  63. }
  64. _onGround = false;
  65. _jumping = false;
  66. Position += _velocity;
  67. }
  68. }
  69. }