Ship.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using Microsoft.Xna.Framework.Input;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Tutorial019.Sprites
  10. {
  11. public class Ship : Sprite
  12. {
  13. public Bullet Bullet;
  14. public Ship(Texture2D texture)
  15. : base(texture)
  16. {
  17. }
  18. public override void Update(GameTime gameTime)
  19. {
  20. _previousKey = _currentKey;
  21. _currentKey = Keyboard.GetState();
  22. if (Keyboard.GetState().IsKeyDown(Keys.A))
  23. _rotation -= MathHelper.ToRadians(RotationVelocity);
  24. else if (Keyboard.GetState().IsKeyDown(Keys.D))
  25. _rotation += MathHelper.ToRadians(RotationVelocity);
  26. Direction = new Vector2((float)Math.Cos(_rotation), (float)Math.Sin(_rotation));
  27. if (Keyboard.GetState().IsKeyDown(Keys.W))
  28. Position += Direction * LinearVelocity;
  29. if (_currentKey.IsKeyDown(Keys.Space) &&
  30. _previousKey.IsKeyUp(Keys.Space))
  31. {
  32. Shoot();
  33. }
  34. }
  35. private void Shoot()
  36. {
  37. var bullet = Bullet.Clone() as Bullet;
  38. bullet.Direction = this.Direction;
  39. bullet.Position = this.Position;
  40. bullet.Colour = this.Colour;
  41. bullet.LinearVelocity = this.LinearVelocity * 1.1f;
  42. bullet.LifeSpan = 3f;
  43. bullet.Parent = this;
  44. Children.Add(bullet);
  45. }
  46. }
  47. }