force.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 body &bodyRef, double k)
  12. {
  13. vec2 dragForce;
  14. if (bodyRef.velocity.magnitudeSquared() > 0)
  15. {
  16. vec2 dragDirection = bodyRef.velocity.unitVector() * -1;
  17. double dragMagnitude = k * bodyRef.velocity.magnitudeSquared();
  18. dragForce = dragDirection * dragMagnitude;
  19. }
  20. return dragForce;
  21. }
  22. vec2 force::generateFrictionForce(const body &bodyRef, double k)
  23. {
  24. vec2 frictionForce;
  25. vec2 frictionDirection = bodyRef.velocity.unitVector() * -1;
  26. double frictionMagnitude = k;
  27. frictionForce = frictionDirection * frictionMagnitude;
  28. return frictionForce;
  29. }
  30. vec2 force::generateGravitationalForce(const body &a, const body &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 body &body, vec2 anchor, double restLength, double k)
  43. {
  44. vec2 d = body.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. }
  51. vec2 force::generateSpringForce(const body &a, const body &b, double restLength, double k)
  52. {
  53. vec2 d = a.position - b.position;
  54. double displacement = d.magnitude() - restLength;
  55. vec2 springDirection = d.unitVector();
  56. double springMagnitude = -k * displacement;
  57. vec2 springForce = springDirection * springMagnitude;
  58. return springForce;
  59. }