Files
aee-arcade/source/game/entities/player.cpp
T

60 lines
2.0 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "game/entities/player.hpp"
#include <SDL3/SDL.h>
#include <algorithm>
#include "core/resources/resource_cache.hpp"
#include "utils/defines.hpp"
namespace {
// Velocitat constant. Si més endavant volem sprint, slow zones, etc.,
// es pot convertir en un membre modificable.
constexpr float SPEED_PX_PER_S = 60.0F;
} // namespace
Player::Player(float x, float y, const Controls& controls)
: AnimatedSprite(Resource::Cache::get().getAnimationData("player.yaml")),
controls_(controls) {
setPos(x, y);
setCurrentAnimation("stand");
}
void Player::update(float delta_time) {
const bool* keys = SDL_GetKeyboardState(nullptr);
float vx = 0.0F;
float vy = 0.0F;
if (keys[controls_.left]) { vx -= SPEED_PX_PER_S; }
if (keys[controls_.right]) { vx += SPEED_PX_PER_S; }
if (keys[controls_.up]) { vy -= SPEED_PX_PER_S; }
if (keys[controls_.down]) { vy += SPEED_PX_PER_S; }
setVelX(vx);
setVelY(vy);
// El sprite original mira a la dreta; flipem només si es mou a l'esquerra
// i restaurem si torna a la dreta. Moviments purament verticals conserven
// l'últim flip perquè el jugador no "gire" sense motiu.
if (vx < 0.0F) {
setFlip(SDL_FLIP_HORIZONTAL);
} else if (vx > 0.0F) {
setFlip(SDL_FLIP_NONE);
}
const bool MOVING = vx != 0.0F || vy != 0.0F;
setCurrentAnimation(MOVING ? "walk" : "stand");
AnimatedSprite::update(delta_time);
// Límits de pantalla amb perspectiva falsa: el cap (12px superiors) pot
// quedar fora per dalt; els peus (12×12 inferiors) sempre dins del canvas.
constexpr auto MIN_X = 0.0F;
constexpr auto MAX_X = static_cast<float>(GameCanvas::WIDTH - SPRITE_WIDTH);
constexpr auto MIN_Y = -static_cast<float>(SPRITE_HEIGHT - COLLISION_HEIGHT);
constexpr auto MAX_Y = static_cast<float>(GameCanvas::HEIGHT - SPRITE_HEIGHT);
setPosX(std::clamp(getPosX(), MIN_X, MAX_X));
setPosY(std::clamp(getPosY(), MIN_Y, MAX_Y));
}