Emitter.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 Tutorial030.Sprites;
  9. namespace Tutorial030.Emitters
  10. {
  11. public abstract class Emitter : Component
  12. {
  13. private float _generateTimer;
  14. private float _swayTimer;
  15. protected Particle _particlePrefab;
  16. protected List<Particle> _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(Particle particle)
  27. {
  28. _particlePrefab = particle;
  29. _particles = new List<Particle>();
  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 Particle 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. }