force.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * 2D Physic Engine
  3. * force.cpp:
  4. * Based on pikuma.com Learn Game Physics Engine Programming course.
  5. * Copyright (c) 2022 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 17/06/2022.
  8. */
  9. #include <physics/force.h>
  10. #include <algorithm>
  11. vec2 force::generateDragForce(const particle &particleRef, double k)
  12. {
  13. vec2 dragForce;
  14. if (particleRef.velocity.magnitudeSquared() > 0)
  15. {
  16. vec2 dragDirection = particleRef.velocity.unitVector() * -1;
  17. double dragMagnitude = k * particleRef.velocity.magnitudeSquared();
  18. dragForce = dragDirection * dragMagnitude;
  19. }
  20. return dragForce;
  21. }
  22. vec2 force::generateFrictionForce(const particle &particleRef, double k)
  23. {
  24. vec2 frictionForce;
  25. vec2 frictionDirection = particleRef.velocity.unitVector() * -1;
  26. double frictionMagnitude = k;
  27. frictionForce = frictionDirection * frictionMagnitude;
  28. return frictionForce;
  29. }
  30. vec2 force::generateGravitationalForce(const particle &a, const particle &b, double g, double minDistance,
  31. double maxDistance)
  32. {
  33. vec2 attractionForce;
  34. vec2 d = b.position - a.position;
  35. double distanceSquared = d.magnitudeSquared();
  36. vec2 attractionDirection = d.unitVector();
  37. distanceSquared = std::clamp(distanceSquared, minDistance, maxDistance);
  38. double attractionMagnitude = g * (a.mass * b.mass) / distanceSquared;
  39. attractionForce = attractionDirection * attractionMagnitude;
  40. return attractionForce;
  41. }
  42. vec2 force::generateSpringForce(const particle &particle, vec2 anchor, double restLength, double k)
  43. {
  44. vec2 d = particle.position - anchor;
  45. double displacement = d.magnitude() - restLength;
  46. vec2 springDirection = d.unitVector();
  47. double springMagnitude = -k * displacement;
  48. vec2 springForce = springDirection * springMagnitude;
  49. return springForce;
  50. }