A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PhysicsTrait.h 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include "../traits/BodyTrait.h"
  3. #include "../common.h"
  4. namespace Swan {
  5. struct PhysicsTrait {
  6. struct Tag {};
  7. struct Physics {
  8. virtual ~Physics() = default;
  9. virtual void applyForce(Vec2 force) = 0;
  10. virtual void addVelocity(Vec2 vel) = 0;
  11. virtual Vec2 getVelocity() = 0;
  12. };
  13. virtual ~PhysicsTrait() = default;
  14. virtual Physics &get(Tag) = 0;
  15. };
  16. struct BasicPhysics final: public PhysicsTrait::Physics {
  17. struct Props {
  18. float mass;
  19. float bounciness = 0;
  20. float mushyness = 2;
  21. };
  22. Vec2 vel{};
  23. Vec2 force{};
  24. bool onGround = false;
  25. void friction(Vec2 coef = Vec2(400, 50));
  26. void gravity(float mass, Vec2 g = Vec2(0, 20));
  27. void standardForces(float mass) { friction(); gravity(mass); }
  28. void applyForce(Vec2 f) override;
  29. void addVelocity(Vec2 v) override;
  30. Vec2 getVelocity() override { return vel; }
  31. void update(
  32. const Swan::Context &ctx, float dt,
  33. BodyTrait::Body &body, const Props &props);
  34. };
  35. /*
  36. * BasicPhysics
  37. */
  38. inline void BasicPhysics::friction(Vec2 coef) {
  39. force += -vel * coef;
  40. }
  41. inline void BasicPhysics::gravity(float mass, Vec2 g) {
  42. force += g * mass;
  43. }
  44. inline void BasicPhysics::applyForce(Vec2 f) {
  45. force += f;
  46. }
  47. inline void BasicPhysics::addVelocity(Vec2 v) {
  48. vel += v;
  49. }
  50. }