Nimbin[12]?SDL & Graphics / sdl3_3d_oop_basic_game / src/entities/player.cpp

sdl3_3d_oop_basic_game git · main

SDL3 3D OOP basic game (entities, systems, CMake)

sdl3 3d c++ game cmake · first commit 2026-04-19 · last commit 2026-04-19 (7 months ago) · synced 1 hour ago · upstream: git.ide3.de/chfis005/sdl3_3d_oop_basic_game

C++ 99%
git clone https://git.christianimmanuel.de/sdl-graphics/sdl3_3d_oop_basic_game.gitwget https://git.christianimmanuel.de/sdl-graphics/sdl3_3d_oop_basic_game/archive/sdl3_3d_oop_basic_game.tar.gz
src/entities/player.cpp 1.5 KB · 66 lines raw
#include "entities/player.hpp"


Player::Player()
    : pos{8.0, 0.0, 8.0},
      vel{0.0, 0.0, 0.0},
      yaw(0x20000000),
      pitch(-0x08000000),
      radius(0.5f),
      height(1.5f)
{}

void Player::applyCollision(const PlayerCollision& col)
{
    pos = col.pos;
    vel = col.vel;
    on_ground = col.hit_y;
}


void Player::respawn(const Vec3& spawn_pos)
{
    pos = spawn_pos;
    vel = {0.0, 0.0, 0.0};
}

void Player::addLook(int dx, int dy)
{
    int32_t delta = dx * 0x00080000;
    int32_t y = static_cast<int32_t>(yaw) - delta;

    yaw   = static_cast<uint32_t>(y);
    pitch = SDL_max(-0x40000000, SDL_min(0x40000000, pitch - dy * 0x00080000));
}

void Player::computeMovement(const PlayerInputState& input)
{
    double rad = (double)yaw * SDL_PI_D / 2147483648.0;
    double c = SDL_cos(rad);
    double s = SDL_sin(rad);

    double dirX = (input.right    ? 1.0 : 0.0) - (input.left    ? 1.0 : 0.0);
    double dirZ = (input.backward ? 1.0 : 0.0) - (input.forward ? 1.0 : 0.0);

    double n = dirX * dirX + dirZ * dirZ;

    acc_x = 0;
    acc_z = 0;

    if (n != 0) {
        double inv = 1.0 / SDL_sqrt(n);
        double mult = 60.0;

        acc_x = mult * ( c*dirX + s*dirZ) * inv;
        acc_z = mult * (-s*dirX + c*dirZ) * inv;
    }
}

Vec3 Player::interpolatedPos(double alpha) const
{
    return {
        prev_pos.x + (pos.x - prev_pos.x) * alpha,
        prev_pos.y + (pos.y - prev_pos.y) * alpha,
        prev_pos.z + (pos.z - prev_pos.z) * alpha
    };
}