Skip to content

L29 — Collision & world response

Goal

Detect pickups with simple sphere checks, keep the player on the island, respawn if they fall.

In plain English

We are not writing a physics engine.

CheckMethod
Collect sharddistance_xz(player, shard) < radius
Stay on islandBox clamp on XZ (e.g. ±5.5) — not a radial cylinder
FallIf y < kill, reset to spawn (pattern; bound is enough here)

Radial “soft walls” skate you around the rim and feel like camera spin — use a box like L28/L30.

What you will see

bash
make -C lessons/l29-collision

Three bobbing starshards; walk into them to collect. Same island/snake/shard scales, push/pop draw pattern, eye-relative move, camYaw, and snake -yaw as L28.

Full lesson source

The blocks below are imported from the real repository files at build time (VitePress <<< snippets). They are not hand-copied into this markdown.

lessons/l29-collision/Makefile · lessons/l29-collision/src/main.c

lessons/l29-collision/Makefile
make
ROMNAME   := l29_hit
ROM_TITLE := "L29 Collision"
USE_T3D   := 1

include ../../common/lesson.mk
lessons/l29-collision/src/main.c
c
/**
 * L29 — Collision & world response
 * ============================================================================
 *
 * LEARNING GOAL
 * -------------
 * Detect pickups without a physics engine:
 *   if distance_xz(player, shard) < radius → collect
 * Soft wall: box clamp on XZ (not radial — radial skates the rim).
 * Kill plane pattern: if y too low, reset (shown as a comment / simple bound).
 *
 * Camera/move match L28: free camYaw, move from lagged eye, snake -yaw.
 * This is intentionally crude. Real games layer better ground probes later.
 *
 * CONTROLS: Stick move, C orbit, walk into crystals
 * DOCS: docs/guide/m4/l29-collision.md
 */


#include <libdragon.h>
#include <t3d/t3d.h>
#include <t3d/t3dmodel.h>
#include <t3d/t3dskeleton.h>
#include <t3d/t3danim.h>
#include <stdio.h>
#include "ng_game.h"

#define FB_COUNT 3
#define SHARD_COUNT 3

typedef struct {
    fm_vec3_t pos;
    bool alive;
} Shard;

static float dist_xz(fm_vec3_t a, fm_vec3_t b)
{
    float dx = a.v[0] - b.v[0];
    float dz = a.v[2] - b.v[2];
    return sqrtf(dx * dx + dz * dz);
}

int main(void)
{
    debug_init_isviewer();
    debug_init_usblog();
    asset_init_compression(2);
    dfs_init(DFS_DEFAULT_LOCATION);
    /* FILTERS_RESAMPLE only — avoid RESAMPLE_ANTIALIAS (1px top-edge flicker). */
    display_init(RESOLUTION_320x240, DEPTH_16_BPP, FB_COUNT, GAMMA_NONE,
                 FILTERS_RESAMPLE);
    rdpq_init();
    joypad_init();
    rdpq_text_register_font(1, rdpq_font_load_builtin(FONT_BUILTIN_DEBUG_VAR));
    t3d_init((T3DInitParams){});

    T3DViewport viewport = t3d_viewport_create_buffered(FB_COUNT);
    T3DMat4FP *playerMat = malloc_uncached(sizeof(T3DMat4FP) * FB_COUNT);
    T3DMat4FP *islandMat = malloc_uncached(sizeof(T3DMat4FP));
    T3DMat4FP *shardMat = malloc_uncached(sizeof(T3DMat4FP) * SHARD_COUNT);
    t3d_mat4fp_from_srt_euler(islandMat,
        (float[3]){ 0.032f, 0.032f, 0.032f }, (float[3]){ 0, 0, 0 }, (float[3]){ 0, 0, 0 });

    T3DModel *island = t3d_model_load("rom:/island.t3dm");
    T3DModel *player = t3d_model_load("rom:/player_anim.t3dm");
    T3DModel *shardM = t3d_model_load("rom:/starshard.t3dm");
    /* Fail loudly (like L27/L28) if any DFS model is missing — otherwise the
     * island/shards/player silently drop out and you get a clear blue screen. */
    assertf(island && player && shardM,
            "L29: failed to load island/player/shards models from ROM (DFS)");

    T3DSkeleton skel = t3d_skeleton_create_buffered(player, FB_COUNT);
    T3DSkeleton skelBlend = t3d_skeleton_clone(&skel, false);
    T3DAnim animIdle = t3d_anim_create(player, "Snake_Idle");
    T3DAnim animWalk = t3d_anim_create(player, "Snake_Walk");
    t3d_anim_attach(&animIdle, &skel);
    t3d_anim_attach(&animWalk, &skelBlend);

    Shard shards[SHARD_COUNT] = {
        { .pos = {{ 3.f, 0.6f, 2.f }}, .alive = true },
        { .pos = {{ -2.5f, 0.6f, 3.f }}, .alive = true },
        { .pos = {{ 1.f, 0.6f, -3.5f }}, .alive = true },
    };

    fm_vec3_t pos = {{ 0, 0.15f, 0 }};
    fm_vec3_t spawn = pos;
    float yaw = 0.f;
    float camYaw = 0.f; /* camera yaw; not player facing */
    fm_vec3_t eye = {{ 0, 8, 14 }};
    fm_vec3_t look = {{ 0, 1, 0 }};
    float last = ng_time_s();
    int frame = 0;
    int collected = 0;
    float bobT = 0.f;
    char line[72];

    uint8_t amb[4] = { 80, 90, 100, 255 };
    uint8_t dirC[4] = { 255, 230, 200, 255 };
    fm_vec3_t ldir = {{ 0.3f, 1.f, 0.25f }};
    fm_vec3_norm(&ldir, &ldir);

    for (;;) {
        joypad_poll();
        joypad_inputs_t in = joypad_get_inputs(JOYPAD_PORT_1);
        float dt = ng_time_s() - last;
        last = ng_time_s();
        frame = (frame + 1) % FB_COUNT;
        bobT += dt;

        if (in.btn.c_left) {
            camYaw -= 1.2f * dt;
        }
        if (in.btn.c_right) {
            camYaw += 1.2f * dt;
        }

        float sx = (float)ng_dz(in.stick_x) / 80.f;
        float sy = (float)ng_dz(in.stick_y) / 80.f;
        float speed = sqrtf(sx * sx + sy * sy);
        if (speed > 1.f) {
            sx /= speed;
            sy /= speed;
            speed = 1.f;
        }
        /* Move relative to lagged camera (eye→player), not player yaw / camYaw alone. */
        float edx = eye.v[0] - pos.v[0];
        float edz = eye.v[2] - pos.v[2];
        float elen = sqrtf(edx * edx + edz * edz);
        float c, s;
        if (elen > 0.001f) {
            float backNow = atan2f(edx, edz);
            c = fm_cosf(backNow);
            s = fm_sinf(backNow);
        } else {
            c = fm_cosf(camYaw);
            s = fm_sinf(camYaw);
        }
        float mx = sx * c - sy * s;
        float mz = -sx * s - sy * c;
        float blend = 0.f;
        if (speed > 0.15f) {
            pos.v[0] += mx * 7.5f * dt;
            pos.v[2] += mz * 7.5f * dt;
            yaw = ng_lerp_angle(yaw, atan2f(mx, mz), 0.22f);

            blend = speed;
        }

        /* Soft wall of island */
        pos.v[0] = ng_clamp(pos.v[0], -5.5f, 5.5f);
        pos.v[2] = ng_clamp(pos.v[2], -5.5f, 5.5f);

        /* Kill plane — if we ever leave the mesh height badly */
        if (pos.v[1] < -2.f) {
            pos = spawn;
        }

        /* Pickups */
        for (int i = 0; i < SHARD_COUNT; i++) {
            if (!shards[i].alive) {
                continue;
            }
            if (dist_xz(pos, shards[i].pos) < 1.1f) {
                shards[i].alive = false;
                collected++;
            }
            float bob = fm_sinf(bobT * 3.f + i) * 0.15f;
            t3d_mat4fp_from_srt_euler(&shardMat[i],
                (float[3]){ 0.02f, 0.02f, 0.02f },
                (float[3]){ 0, bobT + i, 0 },
                (float[3]){ shards[i].pos.v[0], shards[i].pos.v[1] + bob, shards[i].pos.v[2] });
        }

        t3d_anim_update(&animIdle, dt);
        t3d_anim_set_speed(&animWalk, 0.2f + blend);
        t3d_anim_update(&animWalk, dt);
        t3d_skeleton_blend(&skel, &skel, &skelBlend, blend);
        t3d_skeleton_update(&skel);

        float back = camYaw; /* camera sits on camYaw, not player yaw */
        fm_vec3_t eyeWant = {{
            pos.v[0] + fm_sinf(back) * 12.f, pos.v[1] + 6.5f,
            pos.v[2] + fm_cosf(back) * 12.f,
        }};
        fm_vec3_t lookWant = {{ pos.v[0], pos.v[1] + 1.3f, pos.v[2] }};
        float lag = ng_clamp(10.f * dt, 0.08f, 0.4f);
        for (int k = 0; k < 3; k++) {
            eye.v[k] = ng_lerp(eye.v[k], eyeWant.v[k], lag);
            look.v[k] = ng_lerp(look.v[k], lookWant.v[k], lag);
        }

        t3d_viewport_set_projection(&viewport, T3D_DEG_TO_RAD(58.f), 1.f, 200.f);
        t3d_viewport_look_at(&viewport, &eye, &look, &(fm_vec3_t){{ 0, 1, 0 }});
        t3d_mat4fp_from_srt_euler(&playerMat[frame],
            (float[3]){ 0.02f, 0.02f, 0.02f },
            (float[3]){ 0.f, -yaw, 0.f }, /* snake faces -Z */
            (float[3]){ pos.v[0], pos.v[1], pos.v[2] });

        rdpq_attach(display_get(), display_get_zbuf());
        t3d_frame_start();
        t3d_viewport_attach(&viewport);
        t3d_screen_clear_color(RGBA32(25, 50, 90, 0xFF));
        t3d_screen_clear_depth();
        t3d_light_set_ambient(amb);
        t3d_light_set_directional(0, dirC, &ldir);
        t3d_light_set_count(1);

        t3d_matrix_push(islandMat);
        if (island) {
            t3d_model_draw(island);
        }
        t3d_matrix_pop(1);
        for (int i = 0; i < SHARD_COUNT; i++) {
            if (!shards[i].alive) {
                continue;
            }
            t3d_matrix_push(&shardMat[i]);
            if (shardM) {
                t3d_model_draw(shardM);
            }
            t3d_matrix_pop(1);
        }
        t3d_skeleton_use(&skel);
            t3d_matrix_push(&playerMat[frame]);
            t3d_model_draw_skinned(player, &skel);
            t3d_matrix_pop(1);

        rdpq_set_mode_standard();
        rdpq_text_print(NULL, 1, 10, 12, "L29 — Collision pickups");
        snprintf(line, sizeof(line), "Shards %d / %d", collected, SHARD_COUNT);
        rdpq_text_print(NULL, 1, 10, 28, line);
        rdpq_text_print(NULL, 1, 10, 44, "Walk into crystals  soft wall at island edge");

        rdpq_detach_show();
    }
}

Next

L30 — Entities.

N64 Educator v1.2.2 — libdragon + Tiny3D · branch master