Emitter.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Tutorial024.Sprites;
  9. namespace Tutorial024.Emitters
  10. {
  11. public abstract class Emitter : Component
  12. {
  13. private float _generateTimer;
  14. private float _swayTimer;
  15. protected Sprite _particlePrefab;
  16. protected List<Sprite> _particles;
  17. /// <summary>
  18. /// How often a particle is produced
  19. /// </summary>
  20. public float GenerateSpeed = 0.005f;
  21. /// <summary>
  22. /// How often we apply the "GlobalVelociy" to our particles
  23. /// </summary>
  24. public float GlobalVelocitySpeed = 1;
  25. public int MaxParticles = 1000;
  26. public Emitter(Sprite particle)
  27. {
  28. _particlePrefab = particle;
  29. _particles = new List<Sprite>();
  30. }
  31. public override void Update(GameTime gameTime)
  32. {
  33. _generateTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
  34. _swayTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
  35. AddParticle();
  36. if (_swayTimer > GlobalVelocitySpeed)
  37. {
  38. _swayTimer = 0;
  39. ApplyGlobalVelocity();
  40. }
  41. foreach (var particle in _particles)
  42. particle.Update(gameTime);
  43. RemovedFinishedParticles();
  44. }
  45. private void AddParticle()
  46. {
  47. if (_generateTimer > GenerateSpeed)
  48. {
  49. _generateTimer = 0;
  50. if (_particles.Count < MaxParticles)
  51. {
  52. _particles.Add(GenerateParticle());
  53. }
  54. }
  55. }
  56. protected abstract void ApplyGlobalVelocity();
  57. private void RemovedFinishedParticles()
  58. {
  59. for (int i = 0; i < _particles.Count; i++)
  60. {
  61. if (_particles[i].IsRemoved)
  62. {
  63. _particles.RemoveAt(i);
  64. i--;
  65. }
  66. }
  67. }
  68. protected abstract Sprite GenerateParticle();
  69. public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  70. {
  71. foreach (var particle in _particles)
  72. particle.Draw(gameTime, spriteBatch);
  73. }
  74. }
  75. }