Player.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 Tutorial020.Models;
  9. using Microsoft.Xna.Framework.Input;
  10. namespace Tutorial020.Sprites
  11. {
  12. public class Player : Ship
  13. {
  14. private KeyboardState _currentKey;
  15. private KeyboardState _previousKey;
  16. private float _shootTimer = 0;
  17. public bool IsDead
  18. {
  19. get
  20. {
  21. return Health <= 0;
  22. }
  23. }
  24. public Input Input { get; set; }
  25. public Score Score { get; set; }
  26. public Player(Texture2D texture)
  27. : base(texture)
  28. {
  29. Speed = 3f;
  30. }
  31. public override void Update(GameTime gameTime)
  32. {
  33. if (IsDead)
  34. return;
  35. _previousKey = _currentKey;
  36. _currentKey = Keyboard.GetState();
  37. var velocity = Vector2.Zero;
  38. _rotation = 0;
  39. if (_currentKey.IsKeyDown(Input.Up))
  40. {
  41. velocity.Y = -Speed;
  42. _rotation = MathHelper.ToRadians(-15);
  43. }
  44. else if (_currentKey.IsKeyDown(Input.Down))
  45. {
  46. velocity.Y += Speed;
  47. _rotation = MathHelper.ToRadians(15);
  48. }
  49. if (_currentKey.IsKeyDown(Input.Left))
  50. {
  51. velocity.X -= Speed;
  52. }
  53. else if (_currentKey.IsKeyDown(Input.Right))
  54. {
  55. velocity.X += Speed;
  56. }
  57. _shootTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
  58. if (_currentKey.IsKeyDown(Input.Shoot) && _shootTimer > 0.25f)
  59. {
  60. Shoot(Speed * 2);
  61. _shootTimer = 0f;
  62. }
  63. Position += velocity;
  64. Position = Vector2.Clamp(Position, new Vector2(80, 0), new Vector2(Game1.ScreenWidth / 4, Game1.ScreenHeight));
  65. }
  66. public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  67. {
  68. if (IsDead)
  69. return;
  70. base.Draw(gameTime, spriteBatch);
  71. }
  72. public override void OnCollide(Sprite sprite)
  73. {
  74. if (IsDead)
  75. return;
  76. if (sprite is Bullet && ((Bullet)sprite).Parent is Enemy)
  77. Health--;
  78. if (sprite is Enemy)
  79. Health -= 3;
  80. }
  81. }
  82. }