summaryrefslogtreecommitdiff
path: root/platformer/src/player.c
blob: 88df0c4757ca5990e3c2d77ef9a8d6853272758b (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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*
 * ============================================================
 * FILE:        player.c
 *
 * PURPOSE:     The heart of the current milestone: how the character runs,
 *              turns and jumps. Modeled on SM64's approach: an explicit state
 *              machine, speed that follows the analog stick, and a facing
 *              direction that turns toward the stick instead of snapping.
 *
 * FITS IN:     Implements player.h. Reads Input (controls.h). Writes the
 *              Body's velocity, then calls physics_step() (physics.h) to do the
 *              actual motion. Tunables all come from config.h.
 *
 * IMPLEMENT:
 *   - player_init / player_reset: body.pos = spawn, vel = 0, on_ground = true,
 *     body.half_width = PLAYER_HALF_WIDTH, body.height = PLAYER_HEIGHT,
 *     facing_yaw = 0, forward_speed = 0, state = PLAYER_IDLE,
 *     heightened_movement = false, heightened_timer = 0, jump_number = 0.
 *
 *   - player_update(p, in, camera_yaw, dt). Use one static helper per state
 *     (update_idle / update_run / update_jump / update_fall), dispatched by a
 *     `switch (p->state)`. Keep each helper short. Shared steps:
 *
 *     A. Stick -> world direction (camera-relative). Using camera.h's convention:
 *          fwd   = (-sin(camera_yaw), 0, -cos(camera_yaw))
 *          right = ( cos(camera_yaw), 0, -sin(camera_yaw))
 *          wish  = fwd * in->move.y + right * in->move.x
 *          mag   = vec2_length(in->move)          (0..1, already deadzoned)
 *          wish_yaw = atan2f(wish.x, wish.z)      (only meaningful if mag > 0)
 *
 *     B. Ground movement (IDLE / RUN):
 *          - If mag > 0, forward_speed == 0 and wish_yaw is more than
 *              PLAYER_SNAP_TURN_DEG away from facing_yaw: facing_yaw = wish_yaw
 *              at once (standing still, a big turn happens on a dime). Smaller
 *              turns still use the quick turn rate below, so small stick
 *              adjustments stay smooth instead of twitching.
 *          - If mag > 0: facing_yaw = approach_angle(facing_yaw, wish_yaw,
 *              PLAYER_TURN_RATE * dt);  forward_speed = approachf(forward_speed,
 *              PLAYER_MAX_SPEED * mag, PLAYER_GROUND_ACCEL * dt)
 *          - Else: forward_speed = approachf(forward_speed, 0,
 *              PLAYER_GROUND_FRICTION * dt). Accel and friction are low on
 *              purpose: starts build up and stops skid briefly, so the player
 *              feels like a heavy, real object rather than a cursor.
 *          - State: forward_speed > 0 -> RUN, otherwise IDLE.
 *
 *     C. Jump (from IDLE / RUN): if in->jump_pressed and body.on_ground:
 *          on_ground = false; state = JUMP, and then either
 *          - heightened_movement on: the SECOND jump, SM64's double jump.
 *            body.vel.y = PLAYER_SECOND_JUMP_VELOCITY (1.75x the height);
 *            jump_number = 2. heightened_movement stays on for the whole jump,
 *            however long it lasts. Until it lands, the top speed is
 *            PLAYER_SECOND_JUMP_MAX_SPEED instead of PLAYER_MAX_SPEED (see D).
 *          - otherwise a normal jump: body.vel.y = PLAYER_JUMP_VELOCITY;
 *            jump_number = 1.
 *
 *     C2. heightened_movement: landing from a normal jump (jump_number == 1,
 *          short hop or full) turns it on with heightened_timer =
 *          PLAYER_SECOND_JUMP_WINDOW. Landing any other way (from the second
 *          jump, or after walking off an edge) turns it off. Every tick,
 *          unless the player is in the second jump, the timer counts down and
 *          it turns off at 0. WHY a named state rather than a private "can
 *          double jump" flag: later moves will key off it too.
 *
 *     D. Air movement (JUMP / FALL): the same as B, but the turn rate is
 *          multiplied by PLAYER_AIR_CONTROL, accel is PLAYER_AIR_ACCEL, there's
 *          no instant turn from a standstill, and there's NO friction when the
 *          stick is released (you keep your momentum, like SM64).
 *          - Top speed: steering aims for top_speed() * mag, where top_speed()
 *            is PLAYER_SECOND_JUMP_MAX_SPEED while jump_number == 2 and
 *            PLAYER_MAX_SPEED otherwise. While forward_speed is ABOVE it (a
 *            full run into the second jump), the stick only turns: the extra
 *            speed bleeds off at PLAYER_SECOND_JUMP_SLOWDOWN, whatever the
 *            stick does. So a 6 m/s run into the second jump eases down to
 *            5 m/s over ~0.3 s. WHY a separate, gentle rate: slowing at
 *            PLAYER_AIR_ACCEL (~0.25 s) felt like hitting a wall of syrup
 *            right at takeoff. 6 m/s only comes back (through normal ground
 *            accel) after landing. WHY no new state:
 *            jump_number == 2 already means "in the second jump".
 *          - Variable jump height (both jumps): in JUMP, if !in->jump_held and vel.y > 0,
 *            multiply vel.y by PLAYER_JUMP_CUT ONCE (don't repeat it every tick;
 *            either switch to FALL right away or keep a flag). Comment WHY: tapping A
 *            gives a hop, holding it gives a full jump.
 *          - JUMP -> FALL when vel.y <= 0.
 *          - FALL -> IDLE/RUN when body.on_ground (landing; apply C2 first, so
 *            an A press on the landing tick already gets the second jump).
 *          - If the player is on the ground state-wise but body.on_ground is false
 *            (walked off a platform edge) -> FALL.
 *
 *     E. Apply: body.vel.x = sin(facing_yaw) * forward_speed
 *               body.vel.z = cos(facing_yaw) * forward_speed
 *        then physics_step(&p->body, dt).
 *
 *   - player_state_name: a switch that returns string literals.
 *
 * CONVENTIONS: Facing vector = (sin(yaw), 0, cos(yaw)). Speeds are in m/s,
 *              accelerations in m/s^2, and every one of them multiplies by dt.
 *              No magic numbers; everything comes from config.h.
 *
 * NOT IN SCOPE: Triple jump, long jump, wall kick, ground pound,
 *              skidding/turnaround, slopes, coyote time, jump buffering.
 *              Leave a short comment at the state enum pointing to the
 *              README roadmap as the place to grow.
 *
 * DONE WHEN:   Small stick tilts walk slowly and full tilt runs at
 *              PLAYER_MAX_SPEED after a noticeable build-up. Turning is quick but
 *              not instant while moving, and instant for big turns from a standstill. Letting go
 *              of the stick skids the player to a short, smooth stop. A tap of A
 *              gives a short hop and holding A gives a full ~2.4 m jump. Pressing
 *              A within 0.3 s of landing gives a second jump 1.75x as high, with
 *              heightened_movement on from that landing until the second jump
 *              lands. The player lands cleanly back in IDLE/RUN.
 * ============================================================
 */

#include "config.h"
#include "player.h"

/* What the stick is asking for this tick, in world space. */
typedef struct {
    float mag;   /* 0..1, how far the stick is pushed */
    float yaw;   /* world direction to move in; only meaningful if mag > 0 */
} Wish;

static void update_ground(Player *p, const Input *in, Wish wish, float dt);
static void update_fall(Player *p, const Input *in, Wish wish, float dt);

/* A. Stick -> world direction. "Up" on the stick means "away from the
 *    camera", so the stick is rotated by the camera's yaw (camera.h's
 *    convention for forward/right on the ground plane). */
static Wish compute_wish(const Input *in, float camera_yaw)
{
    Vec3 fwd   = vec3_make(-sinf(camera_yaw), 0.0f, -cosf(camera_yaw));
    Vec3 right = vec3_make( cosf(camera_yaw), 0.0f, -sinf(camera_yaw));
    Vec3 dir   = vec3_add(vec3_scale(fwd, in->move.y), vec3_scale(right, in->move.x));

    Wish wish;
    wish.mag = vec2_length(in->move);
    wish.yaw = atan2f(dir.x, dir.z);   /* inverse of facing = (sin(yaw), 0, cos(yaw)) */
    return wish;
}

/* The fastest the player may go right now. The second jump trades
 * horizontal speed for its extra height, until it lands. */
static float top_speed(const Player *p)
{
    return p->jump_number == 2 ? PLAYER_SECOND_JUMP_MAX_SPEED : PLAYER_MAX_SPEED;
}

/* Turns the facing toward the stick, at most turn_rate. */
static void turn(Player *p, Wish wish, float turn_rate, float dt)
{
    p->facing_yaw = approach_angle(p->facing_yaw, wish.yaw, turn_rate * dt);
}

/* Turns toward the stick and speeds up toward a speed set by how far it's
 * pushed. Shared by ground and air movement; the air passes smaller rates. */
static void steer(Player *p, Wish wish, float turn_rate, float accel, float dt)
{
    turn(p, wish, turn_rate, dt);
    p->forward_speed = approachf(p->forward_speed, top_speed(p) * wish.mag, accel * dt);
}

/* Standing still vs walking vs running is only a matter of speed. */
static PlayerState grounded_state(const Player *p)
{
    return p->forward_speed > 0.0f ? PLAYER_RUN : PLAYER_IDLE;
}

/* C. Leaving the ground. While heightened_movement is on (just after landing
 *    a normal jump), A gives the higher second jump instead, like SM64's
 *    double jump. heightened_movement stays on through the whole second jump. */
static void start_jump(Player *p)
{
    if (p->heightened_movement) {
        p->body.vel.y  = PLAYER_SECOND_JUMP_VELOCITY;
        p->jump_number = 2;
    } else {
        p->body.vel.y  = PLAYER_JUMP_VELOCITY;
        p->jump_number = 1;
    }
    p->body.on_ground = false;
    p->state          = PLAYER_JUMP;
}

/* C2. Touching down. Landing a normal jump (a hop or a full one) opens the
 *     short window for the second jump; landing any other way closes it, so
 *     the second jump can't chain into another one. */
static void land(Player *p)
{
    if (p->jump_number == 1) {
        p->heightened_movement = true;
        p->heightened_timer    = PLAYER_SECOND_JUMP_WINDOW;
    } else {
        p->heightened_movement = false;
    }
    p->jump_number = 0;
}

/* C2. The window after landing runs out on its own. It doesn't during the
 *     second jump: heightened_movement lasts as long as that jump does. */
static void count_down_heightened(Player *p, float dt)
{
    if (!p->heightened_movement || p->jump_number == 2)
        return;
    p->heightened_timer -= dt;
    if (p->heightened_timer <= 0.0f)
        p->heightened_movement = false;
}

/* B + C. IDLE and RUN: full control, friction when the stick is released,
 *        and the only place a jump can start. */
static void update_ground(Player *p, const Input *in, Wish wish, float dt)
{
    /* Walked off a platform edge: start falling. */
    if (!p->body.on_ground) {
        p->state = PLAYER_FALL;
        update_fall(p, in, wish, dt);
        return;
    }

    if (wish.mag > 0.0f) {
        /* Standing still there's no momentum to swing around, so a big turn
         * faces the stick right away. Small ones keep the quick turn rate so
         * nudging the stick to adjust your aim still looks smooth. */
        float turn = fabsf(wrap_angle(wish.yaw - p->facing_yaw));
        if (p->forward_speed == 0.0f && turn > PLAYER_SNAP_TURN_DEG * (M3D_PI / 180.0f))
            p->facing_yaw = wish.yaw;
        steer(p, wish, PLAYER_TURN_RATE, PLAYER_GROUND_ACCEL, dt);
    } else {
        p->forward_speed = approachf(p->forward_speed, 0.0f, PLAYER_GROUND_FRICTION * dt);
    }
    p->state = grounded_state(p);

    if (in->jump_pressed)
        start_jump(p);
}

/* D. Air movement: weaker steering, and NO friction when the stick is
 *    released, so you keep your momentum like in SM64. */
static void air_steer(Player *p, Wish wish, float dt)
{
    float air_turn_rate = PLAYER_TURN_RATE * PLAYER_AIR_CONTROL;

    /* Faster than the top speed allows (a full run into the second jump):
     * shed the extra slowly, whatever the stick says, so takeoff doesn't feel
     * like hitting a wall. The stick can still turn. */
    if (p->forward_speed > top_speed(p)) {
        if (wish.mag > 0.0f)
            turn(p, wish, air_turn_rate, dt);
        p->forward_speed = approachf(p->forward_speed, top_speed(p),
                                     PLAYER_SECOND_JUMP_SLOWDOWN * dt);
        return;
    }

    if (wish.mag > 0.0f)
        steer(p, wish, air_turn_rate, PLAYER_AIR_ACCEL, dt);
}

/* FALL: in the air, going down. Landing hands straight over to the ground
 * logic on the same tick, so a jump pressed on the landing tick isn't lost
 * (and already counts as the second jump). */
static void update_fall(Player *p, const Input *in, Wish wish, float dt)
{
    if (p->body.on_ground) {
        land(p);
        p->state = grounded_state(p);
        update_ground(p, in, wish, dt);
        return;
    }
    air_steer(p, wish, dt);
}

/* JUMP: in the air, still rising from a jump. */
static void update_jump(Player *p, const Input *in, Wish wish, float dt)
{
    /* Past the apex (or landed already): it's a fall now. */
    if (p->body.vel.y <= 0.0f) {
        p->state = PLAYER_FALL;
        update_fall(p, in, wish, dt);
        return;
    }

    air_steer(p, wish, dt);

    /* Variable jump height: letting go of A while rising cuts the upward speed.
     * Tapping A gives a short hop, holding it gives the full jump (for the
     * second jump too). Switching to
     * FALL right away makes sure the cut happens only once. */
    if (!in->jump_held) {
        p->body.vel.y *= PLAYER_JUMP_CUT;
        p->state = PLAYER_FALL;
    }
}

void player_init(Player *p, Vec3 spawn)
{
    p->body.pos        = spawn;
    p->body.vel        = vec3_make(0.0f, 0.0f, 0.0f);
    p->body.on_ground  = true;
    p->body.half_width = PLAYER_HALF_WIDTH;   /* the collision box matches the drawn box */
    p->body.height     = PLAYER_HEIGHT;
    p->facing_yaw      = 0.0f;
    p->forward_speed   = 0.0f;
    p->state           = PLAYER_IDLE;
    p->heightened_movement = false;
    p->heightened_timer    = 0.0f;
    p->jump_number         = 0;
}

void player_reset(Player *p, Vec3 spawn)
{
    player_init(p, spawn);
}

void player_update(Player *p, const Input *in, float camera_yaw, float dt)
{
    Wish wish = compute_wish(in, camera_yaw);
    count_down_heightened(p, dt);

    /* IDLE and RUN share one helper: they differ only in speed. */
    switch (p->state) {
    case PLAYER_IDLE:
    case PLAYER_RUN:  update_ground(p, in, wish, dt); break;
    case PLAYER_JUMP: update_jump(p, in, wish, dt);   break;
    case PLAYER_FALL: update_fall(p, in, wish, dt);   break;
    }

    /* E. Turn "speed along facing" into a velocity, then let physics move us. */
    p->body.vel.x = sinf(p->facing_yaw) * p->forward_speed;
    p->body.vel.z = cosf(p->facing_yaw) * p->forward_speed;
    physics_step(&p->body, dt);
}

const char *player_state_name(PlayerState s)
{
    switch (s) {
    case PLAYER_IDLE: return "IDLE";
    case PLAYER_RUN:  return "RUN";
    case PLAYER_JUMP: return "JUMP";
    case PLAYER_FALL: return "FALL";
    }
    return "?";
}