Ship.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 Tutorial006.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, List<Sprite> sprites)
  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. AddBullet(sprites);
  33. }
  34. }
  35. private void AddBullet(List<Sprite> sprites)
  36. {
  37. var bullet = Bullet.Clone() as Bullet;
  38. bullet.Direction = this.Direction;
  39. bullet.Position = this.Position;
  40. bullet.LinearVelocity = this.LinearVelocity * 2;
  41. bullet.LifeSpan = 2f;
  42. bullet.Parent = this;
  43. sprites.Add(bullet);
  44. }
  45. }
  46. }