summaryrefslogtreecommitdiff
path: root/platformer/src/physics.c
blob: 423550defc915152c96d405909d8ad8495e552f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
/*
 * ============================================================
 * FILE:        physics.c
 *
 * PURPOSE:     Moves a Body forward one fixed tick: gravity, then movement one
 *              axis at a time with collision against the level's boxes, and
 *              staying inside the world.
 *
 * FITS IN:     Implements physics.h. Called by player.c inside player_update(),
 *              AFTER the player has chosen its velocity for this tick. Uses
 *              world_floor_below(), world_ceiling_above(), world_find_overlap()
 *              and world_clamp_to_bounds() from world.h.
 *
 * IMPLEMENT physics_step(b, dt), in this order:
 *   1. Gravity ALWAYS pulls: vel.y -= GRAVITY * dt, clamped to no lower than
 *      -TERMINAL_VELOCITY. Standing still, the floor check in step 4 pushes
 *      right back. WHY always: that's what makes walking off a ledge fall on its
 *      own, with no special "is there still floor under me?" case.
 *   2. Move X: pos.x += vel.x * dt. If the body now overlaps a box
 *      (world_find_overlap), push it back out on the side it came from and
 *      zero vel.x. Repeat a few times in case the push lands in another box.
 *   3. Move Z: the same, for z. Resolving one axis at a time is what makes
 *      running diagonally into a wall SLIDE along it instead of stopping dead.
 *   4. Move Y: remember prev_y, then pos.y += vel.y * dt (semi-implicit Euler:
 *      velocity was updated first; add a comment on why that's stable for a
 *      fixed timestep).
 *        Floor: floor = world_floor_below((x, prev_y, z), half_width), the
 *          highest surface the feet were above at the START of the move. If
 *          pos.y <= floor: land (pos.y = floor, vel.y = 0 if falling,
 *          on_ground = true). Using prev_y means a fast fall can never skip
 *          through a thin platform between two ticks.
 *        Otherwise on_ground = false, and check the ceiling the same way from
 *          the previous head height: if the head crossed a box bottom, stop at
 *          it and zero upward speed (bonk).
 *   5. Bounds: pos = world_clamp_to_bounds(pos). If x or z got clamped,
 *      zero that velocity component so the body doesn't "stick" to the edge.
 *
 * CONVENTIONS: dt is always TICK_DT in practice, but use the parameter rather
 *              than the constant so the function stays general.
 *
 * NOT IN SCOPE: Friction/acceleration (that's player movement *intent*, in
 *              player.c), slopes, step-up onto small ledges, sub-stepping.
 *
 * DONE WHEN:   A body placed at y = 10 falls, speeds up, lands exactly on
 *              y = 0 with on_ground = true, and stays there. It lands on
 *              platform tops (even at terminal velocity), can't walk through a
 *              platform's sides, slides along them when running diagonally,
 *              falls when it walks off an edge, and bonks on undersides.
 * ============================================================
 */

#include "config.h"
#include "physics.h"
#include "world.h"

#define PUSH_SKIN       1e-3f   /* m, extra gap left after a push-out so edges only touch */
#define MAX_PUSH_PASSES 4       /* push-outs per axis per tick (boxes can overlap) */

/* Pushes the body out of any box it overlaps along ONE horizontal axis,
 * back toward where it came from. pos_axis/vel_axis point at the x or z
 * members of the body, so the same code handles both axes. */
static void resolve_axis(Body *b, float *pos_axis, float *vel_axis, bool axis_is_x)
{
    for (int pass = 0; pass < MAX_PUSH_PASSES; pass++) {
        Box hit;
        if (!world_find_overlap(b->pos, b->half_width, b->height, &hit))
            return;
        float box_min = axis_is_x ? hit.min.x : hit.min.z;
        float box_max = axis_is_x ? hit.max.x : hit.max.z;
        if (*vel_axis > 0.0f)
            *pos_axis = box_min - b->half_width - PUSH_SKIN;   /* was moving +: back off to the min side */
        else if (*vel_axis < 0.0f)
            *pos_axis = box_max + b->half_width + PUSH_SKIN;   /* was moving -: back off to the max side */
        else
            return;   /* not moving on this axis, so this axis didn't cause it */
        *vel_axis = 0.0f;
    }
}

/* Step 4: vertical movement with floor and ceiling. */
static void move_vertically(Body *b, float dt)
{
    float prev_y = b->pos.y;
    /* Semi-implicit Euler: vel.y was already updated by gravity, and the
     * position moves with that NEW velocity. Unlike plain Euler (which uses
     * the old velocity) it 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.y += b->vel.y * dt;

    /* The highest surface the feet were above BEFORE moving. Any top between
     * the old and new height is at or below prev_y, so the fall lands on the
     * first one it crossed, no matter how fast it was going. */
    float floor_y = world_floor_below(vec3_make(b->pos.x, prev_y, b->pos.z), b->half_width);
    if (b->pos.y <= floor_y) {
        b->pos.y = floor_y;
        if (b->vel.y < 0.0f)
            b->vel.y = 0.0f;
        b->on_ground = true;
        return;
    }
    b->on_ground = false;

    /* Same idea upward: stop the head at the first underside it crossed. */
    float ceiling_y = world_ceiling_above(vec3_make(b->pos.x, prev_y + b->height, b->pos.z),
                                          b->half_width);
    if (b->pos.y + b->height >= ceiling_y) {
        b->pos.y = ceiling_y - b->height;
        if (b->vel.y > 0.0f)
            b->vel.y = 0.0f;
    }
}

void physics_step(Body *b, float dt)
{
    /* 1. Gravity always pulls; the floor pushes back in step 4. */
    b->vel.y -= GRAVITY * dt;
    if (b->vel.y < -TERMINAL_VELOCITY)
        b->vel.y = -TERMINAL_VELOCITY;

    /* 2 + 3. Horizontal movement, one axis at a time, so a diagonal run into
     *        a wall slides along it instead of stopping dead. */
    b->pos.x += b->vel.x * dt;
    resolve_axis(b, &b->pos.x, &b->vel.x, true);
    b->pos.z += b->vel.z * dt;
    resolve_axis(b, &b->pos.z, &b->vel.z, false);

    /* 4. Vertical movement: land on floors, bonk on ceilings. */
    move_vertically(b, dt);

    /* 5. 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;
}