Enemy.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.Graphics;
  7. using Microsoft.Xna.Framework;
  8. namespace Tutorial020.Sprites
  9. {
  10. public class Enemy : Ship
  11. {
  12. private float _timer;
  13. public float ShootingTimer = 1.75f;
  14. public Enemy(Texture2D texture)
  15. : base(texture)
  16. {
  17. Speed = 2f;
  18. }
  19. public override void Update(GameTime gameTime)
  20. {
  21. _timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
  22. if (_timer >= ShootingTimer)
  23. {
  24. Shoot(-5f);
  25. _timer = 0;
  26. }
  27. Position += new Vector2(-Speed, 0);
  28. // if the enemy is off the left side of the screen
  29. if (Position.X < -_texture.Width)
  30. IsRemoved = true;
  31. }
  32. public override void OnCollide(Sprite sprite)
  33. {
  34. // If we crash into a player that is still alive
  35. if (sprite is Player && !((Player)sprite).IsDead)
  36. {
  37. ((Player)sprite).Score.Value++;
  38. // We want to remove the ship completely
  39. IsRemoved = true;
  40. }
  41. // If we hit a bullet that belongs to a player
  42. if (sprite is Bullet && ((Bullet)sprite).Parent is Player)
  43. {
  44. Health--;
  45. if (Health <= 0)
  46. {
  47. IsRemoved = true;
  48. ((Player)sprite.Parent).Score.Value++;
  49. }
  50. }
  51. }
  52. }
  53. }