1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- /*
- * 2D Physic Engine
- * force.cpp:
- * Based on pikuma.com Learn Game Physics Engine Programming course.
- * Copyright (c) 2022 986-Studio. All rights reserved.
- *
- * Created by Manoël Trapier on 17/06/2022.
- */
- #include <physics/force.h>
- #include <algorithm>
- vec2 force::generateDragForce(const body &bodyRef, double k)
- {
- vec2 dragForce;
- if (bodyRef.velocity.magnitudeSquared() > 0)
- {
- vec2 dragDirection = bodyRef.velocity.unitVector() * -1;
- double dragMagnitude = k * bodyRef.velocity.magnitudeSquared();
- dragForce = dragDirection * dragMagnitude;
- }
- return dragForce;
- }
- vec2 force::generateFrictionForce(const body &bodyRef, double k)
- {
- vec2 frictionForce;
- vec2 frictionDirection = bodyRef.velocity.unitVector() * -1;
- double frictionMagnitude = k;
- frictionForce = frictionDirection * frictionMagnitude;
- return frictionForce;
- }
- vec2 force::generateGravitationalForce(const body &a, const body &b, double g, double minDistance,
- double maxDistance)
- {
- vec2 attractionForce;
- vec2 d = b.position - a.position;
- double distanceSquared = d.magnitudeSquared();
- vec2 attractionDirection = d.unitVector();
- distanceSquared = std::clamp(distanceSquared, minDistance, maxDistance);
- double attractionMagnitude = g * (a.mass * b.mass) / distanceSquared;
- attractionForce = attractionDirection * attractionMagnitude;
- return attractionForce;
- }
- vec2 force::generateSpringForce(const body &body, vec2 anchor, double restLength, double k)
- {
- vec2 d = body.position - anchor;
- double displacement = d.magnitude() - restLength;
- vec2 springDirection = d.unitVector();
- double springMagnitude = -k * displacement;
- vec2 springForce = springDirection * springMagnitude;
- return springForce;
- }
- vec2 force::generateSpringForce(const body &a, const body &b, double restLength, double k)
- {
- vec2 d = a.position - b.position;
- double displacement = d.magnitude() - restLength;
- vec2 springDirection = d.unitVector();
- double springMagnitude = -k * displacement;
- vec2 springForce = springDirection * springMagnitude;
- return springForce;
- }
|