LinearGravityModifier.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) Craftwork Games. All rights reserved.
  2. // Licensed under the MIT license.
  3. // See LICENSE file in the project root for full license information.
  4. using Microsoft.Xna.Framework;
  5. using MonoGame.Extended.Particles.Data;
  6. namespace MonoGame.Extended.Particles.Modifiers;
  7. /// <summary>
  8. /// A modifier that applies a constant directional force to particles, simulating gravity or wind.
  9. /// </summary>
  10. /// <remarks>
  11. /// The <see cref="LinearGravityModifier"/> applies a uniform acceleration in a specified direction
  12. /// to all particles, creating effects such as gravity, wind, or other constant forces. The force
  13. /// is applied proportionally to each particle's mass, simulating realistic physical behavior.
  14. ///
  15. /// Note that this modifier only changes particle velocities; the actual position changes
  16. /// occur during the standard particle update cycle.
  17. /// </remarks>
  18. public class LinearGravityModifier : Modifier
  19. {
  20. /// <summary>
  21. /// Gets or sets the direction vector of the gravitational force.
  22. /// </summary>
  23. /// <remarks>
  24. /// This vector defines both the direction and the relative magnitude of the force.
  25. /// </remarks>
  26. public Vector2 Direction { get; set; }
  27. /// <summary>
  28. /// Gets or sets the strength of the gravitational force, in units per second squared.
  29. /// </summary>
  30. /// <remarks>
  31. /// This value scales the overall magnitude of the force. Higher values create
  32. /// stronger acceleration effects, causing particles to change velocity more rapidly.
  33. /// </remarks>
  34. public float Strength { get; set; }
  35. /// <summary>
  36. /// Updates all particles by applying a linear gravitational force.
  37. /// </summary>
  38. /// <inheritdoc/>
  39. protected internal override unsafe void Update(float elapsedSeconds, ParticleIterator iterator, int particleCount)
  40. {
  41. if (!Enabled) { return; }
  42. Vector2 vector = Direction * (Strength * elapsedSeconds);
  43. for (int i = 0; i < particleCount && iterator.HasNext; i++)
  44. {
  45. Particle* particle = iterator.Next();
  46. particle->Velocity[0] = particle->Velocity[0] + vector.X * particle->Mass;
  47. particle->Velocity[1] = particle->Velocity[1] + vector.Y * particle->Mass;
  48. }
  49. }
  50. }