Bullet.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 Bullet : Sprite, ICollidable
  11. {
  12. private float _timer;
  13. public Explosion Explosion;
  14. public float LifeSpan { get; set; }
  15. public Vector2 Velocity { get; set; }
  16. public Bullet(Texture2D texture)
  17. : base(texture)
  18. {
  19. }
  20. public override void Update(GameTime gameTime)
  21. {
  22. _timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
  23. if (_timer >= LifeSpan)
  24. IsRemoved = true;
  25. Position += Velocity;
  26. }
  27. public void OnCollide(Sprite sprite)
  28. {
  29. //switch (sprite)
  30. //{
  31. // case Bullet b:
  32. // return;
  33. // case Enemy e1 when e1.Parent is Enemy:
  34. // if (e1.Parent is Enemy)
  35. // return;
  36. // if()
  37. // return;
  38. // case Enemy e2 when
  39. // case Player p when (p.IsDead || p.Parent is Player):
  40. // return;
  41. //}
  42. // Bullets don't collide with eachother
  43. if (sprite is Bullet)
  44. return;
  45. // Enemies can't shoot eachother
  46. if (sprite is Enemy && this.Parent is Enemy)
  47. return;
  48. // Players can't shoot eachother
  49. if (sprite is Player && this.Parent is Player)
  50. return;
  51. // Can't hit a player if they're dead
  52. if (sprite is Player && ((Player)sprite).IsDead)
  53. return;
  54. if (sprite is Enemy && this.Parent is Player)
  55. {
  56. IsRemoved = true;
  57. AddExplosion();
  58. }
  59. if(sprite is Player && this.Parent is Enemy)
  60. {
  61. IsRemoved = true;
  62. AddExplosion();
  63. }
  64. }
  65. private void AddExplosion()
  66. {
  67. if (Explosion == null)
  68. return;
  69. var explosion = Explosion.Clone() as Explosion;
  70. explosion.Position = this.Position;
  71. Children.Add(explosion);
  72. }
  73. }
  74. }