Input + moviment del jugador amb fletxes (flip, anim walk/stand, bounds) (v0.8.0)

This commit is contained in:
JailDesigner committed 2026-04-19 09:57:22 +02:00
1 parent bee9b650db
commit 96cbdf96b6
5 files changed
+99 -18

No files matched your search

+53 -3
View File
@@ -1,9 +1,59 @@
#include "game/entities/player.hpp"
#include "core/resources/resource_cache.hpp"
#include <SDL3/SDL.h>
Player::Player(float x, float y)
: AnimatedSprite(Resource::Cache::get().getAnimationData("player.yaml")) {
#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));
}