summaryrefslogtreecommitdiff
path: root/platformer/src/physics.c
diff options
context:
space:
mode:
Diffstat (limited to 'platformer/src/physics.c')
-rw-r--r--platformer/src/physics.c42
1 files changed, 42 insertions, 0 deletions
diff --git a/platformer/src/physics.c b/platformer/src/physics.c
index 3608c48..b04a78e 100644
--- a/platformer/src/physics.c
+++ b/platformer/src/physics.c
@@ -38,3 +38,45 @@
* y = 0 with on_ground = true, and stays there.
* ============================================================
*/
+
+#include "config.h"
+#include "physics.h"
+#include "world.h"
+
+void physics_step(Body *b, float dt)
+{
+ /* 1. Gravity. On the ground vel.y is left alone: a jump sets it positive
+ * before this call, and that's what lifts the body off the ground. */
+ if (!b->on_ground) {
+ b->vel.y -= GRAVITY * dt;
+ if (b->vel.y < -TERMINAL_VELOCITY)
+ b->vel.y = -TERMINAL_VELOCITY;
+ }
+
+ /* 2. Integrate with semi-implicit Euler: velocity was updated above, and
+ * position now moves with that NEW velocity. Unlike plain Euler (which
+ * uses the old velocity) this doesn't gain energy over time, and with a
+ * fixed dt the result is identical every run, so a jump always
+ * reaches the same height. */
+ b->pos = vec3_add(b->pos, vec3_scale(b->vel, dt));
+
+ /* 3. Ground. Landing snaps the feet to the surface and kills the downward
+ * speed. on_ground goes false the moment a jump lifts the body (and,
+ * once terrain exists, when walking off a ledge). */
+ float ground = world_ground_height(b->pos.x, b->pos.z);
+ if (b->pos.y <= ground) {
+ b->pos.y = ground;
+ if (b->vel.y < 0.0f)
+ b->vel.y = 0.0f;
+ b->on_ground = true;
+ } else {
+ b->on_ground = false;
+ }
+
+ /* 4. Bounds. Zero the velocity into an edge we got clamped against, so
+ * the body doesn't "stick" to it while pushing into it. */
+ Vec3 clamped = world_clamp_to_bounds(b->pos);
+ if (clamped.x != b->pos.x) b->vel.x = 0.0f;
+ if (clamped.z != b->pos.z) b->vel.z = 0.0f;
+ b->pos = clamped;
+}