From 23ef8bc20310bdfad52b07a3f1e4e61c98896841 Mon Sep 17 00:00:00 2001 From: Schark Date: Wed, 23 Sep 2026 23:40:11 -0400 Subject: Working demogit add README.md src/ --- platformer/src/camera.c | 66 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) (limited to 'platformer/src/camera.c') diff --git a/platformer/src/camera.c b/platformer/src/camera.c index 00f8d4a..531d58c 100644 --- a/platformer/src/camera.c +++ b/platformer/src/camera.c @@ -49,3 +49,69 @@ * player slightly without jitter. * ============================================================ */ + +#include "camera.h" +#include "config.h" + +/* The point the camera wants to look at: a bit above the player's feet. */ +static Vec3 desired_target(Vec3 follow_point) +{ + return vec3_add(follow_point, vec3_make(0.0f, CAMERA_TARGET_HEIGHT, 0.0f)); +} + +/* The YAW CONVENTION from camera.h. player.c depends on this exact formula. */ +static void recompute_position(Camera *c) +{ + Vec3 offset = vec3_make(sinf(c->yaw) * cosf(c->pitch), + sinf(c->pitch), + cosf(c->yaw) * cosf(c->pitch)); + c->position = vec3_add(c->target, vec3_scale(offset, c->distance)); +} + +void camera_init(Camera *c, Vec3 follow_point) +{ + c->target = desired_target(follow_point); /* snap, no smoothing */ + c->yaw = 0.0f; /* on +Z, looking toward -Z */ + c->pitch = CAMERA_PITCH_DEFAULT; + c->distance = CAMERA_DISTANCE; + recompute_position(c); +} + +void camera_update(Camera *c, const Input *in, Vec3 follow_point, float dt) +{ + /* 1. Orbit. The yaw sign is flipped (-=): pushing the stick RIGHT should + * turn the VIEW right, which means the camera swings LEFT around the + * player. The camera's forward is (-sin(yaw), 0, -cos(yaw)), so turning it + * toward the camera's right (+X at yaw 0) needs yaw to DECREASE. */ + c->yaw -= in->look.x * CAMERA_YAW_SPEED * dt; + c->pitch += in->look.y * CAMERA_PITCH_SPEED * dt; + c->pitch = clampf(c->pitch, CAMERA_PITCH_MIN, CAMERA_PITCH_MAX); + c->yaw = wrap_angle(c->yaw); + + /* 2. Follow with exponential smoothing. A camera that snaps rigidly to the + * player looks jittery, and a little lag lets you see the motion. Using + * 1 - e^(-rate*dt) instead of a fixed lerp factor keeps the catch-up speed + * the same regardless of the tick rate. */ + float t = 1.0f - expf(-CAMERA_FOLLOW_RATE * dt); + c->target = vec3_lerp(c->target, desired_target(follow_point), t); + + /* 3. Place the eye on the orbit sphere around the new target. */ + recompute_position(c); +} + +float camera_yaw(const Camera *c) +{ + return c->yaw; +} + +Mat4 camera_view(const Camera *c) +{ + return mat4_look_at(c->position, c->target, vec3_make(0.0f, 1.0f, 0.0f)); +} + +Mat4 camera_projection(const Camera *c, float aspect) +{ + (void)c; /* every camera shares the same lens for now */ + float fovy_rad = CAMERA_FOV_DEG * (M3D_PI / 180.0f); + return mat4_perspective(fovy_rad, aspect, CAMERA_NEAR, CAMERA_FAR); +} -- cgit v1.2.3-18-g5258