2
0

SimpleWindForce.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using FarseerPhysics.Dynamics;
  2. using Microsoft.Xna.Framework;
  3. namespace FarseerPhysics.Controllers
  4. {
  5. /// <summary>
  6. /// Reference implementation for forces based on AbstractForceController
  7. /// It supports all features provided by the base class and illustrates proper
  8. /// usage as an easy to understand example.
  9. /// As a side-effect it is a nice and easy to use wind force for your projects
  10. /// </summary>
  11. public class SimpleWindForce : AbstractForceController
  12. {
  13. /// <summary>
  14. /// Direction of the windforce
  15. /// </summary>
  16. public Vector2 Direction { get; set; }
  17. /// <summary>
  18. /// The amount of Direction randomization. Allowed range is 0-1.
  19. /// </summary>
  20. public float Divergence { get; set; }
  21. /// <summary>
  22. /// Ignore the position and apply the force. If off only in the "front" (relative to position and direction)
  23. /// will be affected
  24. /// </summary>
  25. public bool IgnorePosition { get; set; }
  26. public override void ApplyForce(float dt, float strength)
  27. {
  28. foreach (Body body in World.BodyList)
  29. {
  30. //TODO: Consider Force Type
  31. float decayMultiplier = GetDecayMultiplier(body);
  32. if (decayMultiplier != 0)
  33. {
  34. Vector2 forceVector;
  35. if (ForceType == ForceTypes.Point)
  36. {
  37. forceVector = body.Position - Position;
  38. }
  39. else
  40. {
  41. Direction.Normalize();
  42. forceVector = Direction;
  43. if (forceVector.Length() == 0)
  44. forceVector = new Vector2(0, 1);
  45. }
  46. //TODO: Consider Divergence:
  47. //forceVector = Vector2.Transform(forceVector, Matrix.CreateRotationZ((MathHelper.Pi - MathHelper.Pi/2) * (float)Randomize.NextDouble()));
  48. // Calculate random Variation
  49. if (Variation != 0)
  50. {
  51. float strengthVariation = (float)Randomize.NextDouble() * MathHelper.Clamp(Variation, 0, 1);
  52. forceVector.Normalize();
  53. body.ApplyForce(forceVector * strength * decayMultiplier * strengthVariation);
  54. }
  55. else
  56. {
  57. forceVector.Normalize();
  58. body.ApplyForce(forceVector * strength * decayMultiplier);
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }