diff options
author | Matthew Kosarek <mattkae@protonmail.com> | 2021-06-22 20:23:33 -0400 |
---|---|---|
committer | Matthew Kosarek <mattkae@protonmail.com> | 2021-06-22 20:23:33 -0400 |
commit | f34116f1da8465851d684620b6b94e0a3f3c0fbc (patch) | |
tree | d17c3531f017caa3c60bc66a96d804d03fa60b21 /2d/rigidbody/rigidbody_1/snippet3.cpp | |
parent | a36f425491aaf019243a31179e80cb10ea62db59 (diff) |
Impulses, and entirely finished with rigid body demo #1
Diffstat (limited to '2d/rigidbody/rigidbody_1/snippet3.cpp')
-rw-r--r-- | 2d/rigidbody/rigidbody_1/snippet3.cpp | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/2d/rigidbody/rigidbody_1/snippet3.cpp b/2d/rigidbody/rigidbody_1/snippet3.cpp new file mode 100644 index 0000000..a43c884 --- /dev/null +++ b/2d/rigidbody/rigidbody_1/snippet3.cpp @@ -0,0 +1,66 @@ +struct Impulse { + Vector2 force = { 0, 0 }; + float32 timeOfApplicationSeconds = 0.25f; + float32 timeAppliedSeconds = 0.f; + bool isDead = false; +}; + +const int32 NUM_IMPULSES = 4; + +struct Rigidbody { + int32 numImpulses = 0; + Impulse activeImpulses[NUM_IMPULSES]; + Vector2 velocity = { 0, 0 }; + Vector2 position = { 0, 0 }; + float32 mass = 1.f; + + void update(float32 deltaTimeSeconds) { + applyGravity(deltaTimeSeconds); + + // Add up all of the forces acting at this moment + Vector2 force; + for (int32 idx = 0; idx < numImpulses; idx++) { + Impulse& i = activeImpulses[idx]; + + float32 nextTimeAppliedSeconds = i.timeAppliedSeconds + deltaTimeSeconds; + if (nextTimeAppliedSeconds >= i.timeOfApplicationSeconds) { + nextTimeAppliedSeconds = i.timeOfApplicationSeconds; + i.isDead = true; + } + + float32 impulseDtSeconds = nextTimeAppliedSeconds - i.timeAppliedSeconds; + force += i.force * impulseDtSeconds; + i.timeAppliedSeconds = nextTimeAppliedSeconds; + } + + Vector2 acceleration = force / mass; + velocity += (acceleration * impulseDtSeconds); + position += (velocity * deltaTimeSeconds); + + // Cleanup any impulses that have expired in the mean time + for (int32 idx = 0; idx < numImpulses; idx++) { + if (activeImpulses[idx].isDead) { + for (int j = idx + 1; j < numImpulses; j++) { + activeImpulses[j - 1] = activeImpulses[j]; + } + + idx = idx - 1; + numImpulses--; + } + } + } + + void applyGravity(float32 deltaTimeSeconds) { + velocity += (Vector2 { 0.f, -9.8f } * deltaTimeSeconds); + } + + void applyImpulse(Impulse i) { + if (numImpulses > NUM_IMPULSES) { + printf("Unable to apply impulse. Buffer full.\n"); + return; + } + + activeImpulses[numImpulses] = i; + numImpulses++; + } +}; |