migrat Game, Player i Item a time based

This commit is contained in:
2025-10-28 10:52:13 +01:00
parent 9e8c5e13df
commit 31c84f9676
8 changed files with 190 additions and 153 deletions

View File

@@ -49,19 +49,21 @@ void Player::render() {
}
// Actualiza las variables del objeto
void Player::update() {
void Player::update(float delta_time) {
if (!is_paused_) {
checkInput(); // Comprueba las entradas y modifica variables
move(); // Recalcula la posición del jugador
animate(); // Establece la animación del jugador
checkBorders(); // Comprueba si está situado en alguno de los cuatro bordes de la habitación
checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
checkKillingTiles(); // Comprueba que el jugador no toque ningun tile de los que matan}
checkInput(delta_time); // Comprueba las entradas y modifica variables
move(delta_time); // Recalcula la posición del jugador
animate(delta_time); // Establece la animación del jugador
checkBorders(); // Comprueba si está situado en alguno de los cuatro bordes de la habitación
checkJumpEnd(); // Comprueba si ha finalizado el salto al alcanzar la altura de inicio
checkKillingTiles(); // Comprueba que el jugador no toque ningun tile de los que matan}
}
}
// Comprueba las entradas y modifica variables
void Player::checkInput() {
void Player::checkInput(float delta_time) {
(void)delta_time; // No usado en este método, pero mantenido para consistencia
// Solo comprueba las entradas de dirección cuando está sobre una superficie
if (state_ != PlayerState::STANDING) {
return;
@@ -70,12 +72,12 @@ void Player::checkInput() {
if (!auto_movement_) {
// Comprueba las entradas de desplazamiento lateral solo en el caso de no estar enganchado a una superficie automatica
if (Input::get()->checkInput(InputAction::LEFT)) {
vx_ = -0.6F;
vx_ = -HORIZONTAL_VELOCITY;
sprite_->setFlip(SDL_FLIP_HORIZONTAL);
}
else if (Input::get()->checkInput(InputAction::RIGHT)) {
vx_ = 0.6F;
vx_ = HORIZONTAL_VELOCITY;
sprite_->setFlip(SDL_FLIP_NONE);
}
@@ -88,7 +90,7 @@ void Player::checkInput() {
}
}
} else { // El movimiento lo proporciona la superficie
vx_ = 0.6F * room_->getAutoSurfaceDirection();
vx_ = HORIZONTAL_VELOCITY * room_->getAutoSurfaceDirection();
if (vx_ > 0.0F) {
sprite_->setFlip(SDL_FLIP_NONE);
@@ -105,9 +107,9 @@ void Player::checkInput() {
if (isOnFloor() || isOnAutoSurface()) {
setState(PlayerState::JUMPING);
vy_ = -MAX_VY;
vy_ = JUMP_VELOCITY;
jump_init_pos_ = y_;
jumping_counter_ = 0;
jumping_time_ = 0.0F;
}
}
}
@@ -140,34 +142,36 @@ void Player::checkBorders() {
}
// Comprueba el estado del jugador
void Player::checkState() {
void Player::checkState(float delta_time) {
// Actualiza las variables en función del estado
if (state_ == PlayerState::FALLING) {
vx_ = 0.0F;
vy_ = MAX_VY;
falling_counter_++;
falling_time_ += delta_time;
playFallSound();
}
else if (state_ == PlayerState::STANDING) {
if (previous_state_ == PlayerState::FALLING && falling_counter_ > MAX_FALLING_HEIGHT) { // Si cae de muy alto, el jugador muere
// Calcula la distancia de caída en pixels (velocidad * tiempo)
const float FALLING_DISTANCE = MAX_VY * falling_time_;
if (previous_state_ == PlayerState::FALLING && FALLING_DISTANCE > MAX_FALLING_HEIGHT) { // Si cae de muy alto, el jugador muere
is_alive_ = false;
}
vy_ = 0.0F;
jumping_counter_ = 0;
falling_counter_ = 0;
jumping_time_ = 0.0F;
falling_time_ = 0.0F;
if (!isOnFloor() && !isOnAutoSurface() && !isOnDownSlope()) {
setState(PlayerState::FALLING);
vx_ = 0.0F;
vy_ = MAX_VY;
falling_counter_++;
falling_time_ += delta_time;
playFallSound();
}
}
else if (state_ == PlayerState::JUMPING) {
falling_counter_ = 0;
jumping_counter_++;
falling_time_ = 0.0F;
jumping_time_ += delta_time;
playJumpSound();
}
}
@@ -203,25 +207,24 @@ void Player::switchBorders() {
}
// Aplica gravedad al jugador
void Player::applyGravity() {
constexpr float GRAVITY_FORCE = 0.035F;
void Player::applyGravity(float delta_time) {
// La gravedad solo se aplica cuando el jugador esta saltando
// Nunca mientras cae o esta de pie
if (state_ == PlayerState::JUMPING) {
vy_ += GRAVITY_FORCE;
vy_ += GRAVITY_FORCE * delta_time;
vy_ = std::min(vy_, MAX_VY);
}
}
// Maneja el movimiento horizontal hacia la izquierda
void Player::moveHorizontalLeft() {
void Player::moveHorizontalLeft(float delta_time) {
// Crea el rectangulo de proyección en el eje X para ver si colisiona
const float DISPLACEMENT = vx_ * delta_time;
SDL_FRect proj;
proj.x = static_cast<int>(x_ + vx_);
proj.x = static_cast<int>(x_ + DISPLACEMENT);
proj.y = static_cast<int>(y_);
proj.h = HEIGHT;
proj.w = static_cast<int>(std::ceil(std::fabs(vx_))); // Para evitar que tenga un ancho de 0 pixels
proj.w = static_cast<int>(std::ceil(std::fabs(DISPLACEMENT))); // Para evitar que tenga un ancho de 0 pixels
#ifdef _DEBUG
debug_rect_x_ = proj;
@@ -233,7 +236,7 @@ void Player::moveHorizontalLeft() {
// Calcula la nueva posición
if (POS == -1) {
// Si no hay colisión
x_ += vx_;
x_ += DISPLACEMENT;
} else {
// Si hay colisión lo mueve hasta donde no colisiona
x_ = POS + 1;
@@ -255,13 +258,14 @@ void Player::moveHorizontalLeft() {
}
// Maneja el movimiento horizontal hacia la derecha
void Player::moveHorizontalRight() {
void Player::moveHorizontalRight(float delta_time) {
// Crea el rectangulo de proyección en el eje X para ver si colisiona
const float DISPLACEMENT = vx_ * delta_time;
SDL_FRect proj;
proj.x = x_ + WIDTH;
proj.y = y_;
proj.h = HEIGHT;
proj.w = std::ceil(vx_); // Para evitar que tenga un ancho de 0 pixels
proj.w = std::ceil(DISPLACEMENT); // Para evitar que tenga un ancho de 0 pixels
#ifdef _DEBUG
debug_rect_x_ = proj;
@@ -273,7 +277,7 @@ void Player::moveHorizontalRight() {
// Calcula la nueva posición
if (POS == -1) {
// Si no hay colisión
x_ += vx_;
x_ += DISPLACEMENT;
} else {
// Si hay colisión lo mueve hasta donde no colisiona
x_ = POS - WIDTH;
@@ -295,12 +299,13 @@ void Player::moveHorizontalRight() {
}
// Maneja el movimiento vertical hacia arriba
void Player::moveVerticalUp() {
void Player::moveVerticalUp(float delta_time) {
// Crea el rectangulo de proyección en el eje Y para ver si colisiona
const float DISPLACEMENT = vy_ * delta_time;
SDL_FRect proj;
proj.x = static_cast<int>(x_);
proj.y = static_cast<int>(y_ + vy_);
proj.h = static_cast<int>(std::ceil(std::fabs(vy_))); // Para evitar que tenga una altura de 0 pixels
proj.y = static_cast<int>(y_ + DISPLACEMENT);
proj.h = static_cast<int>(std::ceil(std::fabs(DISPLACEMENT))); // Para evitar que tenga una altura de 0 pixels
proj.w = WIDTH;
#ifdef _DEBUG
@@ -313,7 +318,7 @@ void Player::moveVerticalUp() {
// Calcula la nueva posición
if (POS == -1) {
// Si no hay colisión
y_ += vy_;
y_ += DISPLACEMENT;
} else {
// Si hay colisión lo mueve hasta donde no colisiona y entra en caída
y_ = POS + 1;
@@ -322,12 +327,13 @@ void Player::moveVerticalUp() {
}
// Maneja el movimiento vertical hacia abajo
void Player::moveVerticalDown() {
void Player::moveVerticalDown(float delta_time) {
// Crea el rectangulo de proyección en el eje Y para ver si colisiona
const float DISPLACEMENT = vy_ * delta_time;
SDL_FRect proj;
proj.x = x_;
proj.y = y_ + HEIGHT;
proj.h = std::ceil(vy_); // Para evitar que tenga una altura de 0 pixels
proj.h = std::ceil(DISPLACEMENT); // Para evitar que tenga una altura de 0 pixels
proj.w = WIDTH;
#ifdef _DEBUG
@@ -362,7 +368,7 @@ void Player::moveVerticalDown() {
} else {
// No está saltando y no hay colisón con una rampa
// Calcula la nueva posición
y_ += vy_;
y_ += DISPLACEMENT;
#ifdef _DEBUG
debug_color_ = static_cast<Uint8>(PaletteColor::RED);
#endif
@@ -370,16 +376,16 @@ void Player::moveVerticalDown() {
} else {
// Esta saltando y no hay colisión con los muros
// Calcula la nueva posición
y_ += vy_;
y_ += DISPLACEMENT;
}
}
}
// Recalcula la posición del jugador y su animación
void Player::move() {
void Player::move(float delta_time) {
last_position_ = {.x = x_, .y = y_}; // Guarda la posicion actual antes de modificarla
applyGravity(); // Aplica gravedad al jugador
checkState(); // Comprueba el estado del jugador
applyGravity(delta_time); // Aplica gravedad al jugador
checkState(delta_time); // Comprueba el estado del jugador
#ifdef _DEBUG
debug_color_ = static_cast<Uint8>(PaletteColor::GREEN);
@@ -387,9 +393,9 @@ void Player::move() {
// Movimiento horizontal
if (vx_ < 0.0F) {
moveHorizontalLeft();
moveHorizontalLeft(delta_time);
} else if (vx_ > 0.0F) {
moveHorizontalRight();
moveHorizontalRight(delta_time);
}
// Si ha salido del suelo, el jugador cae
@@ -405,9 +411,9 @@ void Player::move() {
// Movimiento vertical
if (vy_ < 0.0F) {
moveVerticalUp();
moveVerticalUp(delta_time);
} else if (vy_ > 0.0F) {
moveVerticalDown();
moveVerticalDown(delta_time);
}
placeSprite(); // Coloca el sprite en la nueva posición
@@ -420,9 +426,9 @@ void Player::move() {
}
// Establece la animación del jugador
void Player::animate() {
void Player::animate(float delta_time) {
if (vx_ != 0) {
sprite_->update();
sprite_->update(delta_time);
}
}
@@ -434,7 +440,7 @@ void Player::checkJumpEnd() {
// Si alcanza la altura de salto inicial, pasa al estado de caída
setState(PlayerState::FALLING);
vy_ = MAX_VY;
jumping_counter_ = 0;
jumping_time_ = 0.0F;
}
}
}
@@ -442,24 +448,31 @@ void Player::checkJumpEnd() {
// Calcula y reproduce el sonido de salto
void Player::playJumpSound() {
if (jumping_counter_ % 4 == 0) {
JA_PlaySound(jumping_sound_[jumping_counter_ / 4]);
}
const int SOUND_INDEX = static_cast<int>(jumping_time_ / SOUND_INTERVAL);
const int PREVIOUS_INDEX = static_cast<int>((jumping_time_ - SOUND_INTERVAL) / SOUND_INTERVAL);
// Solo reproduce el sonido cuando cambia de índice
if (SOUND_INDEX != PREVIOUS_INDEX && SOUND_INDEX < static_cast<int>(jumping_sound_.size())) {
JA_PlaySound(jumping_sound_[SOUND_INDEX]);
#ifdef _DEBUG
Debug::get()->add("JUMP: " + std::to_string(jumping_counter_ / 4));
Debug::get()->add("JUMP: " + std::to_string(SOUND_INDEX));
#endif
}
}
// Calcula y reproduce el sonido de caer
void Player::playFallSound() {
if (falling_counter_ % 4 == 0) {
JA_PlaySound(falling_sound_[std::min((falling_counter_ / 4), (int)falling_sound_.size() - 1)]);
}
const int SOUND_INDEX = static_cast<int>(falling_time_ / SOUND_INTERVAL);
const int PREVIOUS_INDEX = static_cast<int>((falling_time_ - SOUND_INTERVAL) / SOUND_INTERVAL);
// Solo reproduce el sonido cuando cambia de índice
if (SOUND_INDEX != PREVIOUS_INDEX) {
const int CLAMPED_INDEX = std::min(SOUND_INDEX, static_cast<int>(falling_sound_.size()) - 1);
JA_PlaySound(falling_sound_[CLAMPED_INDEX]);
#ifdef _DEBUG
Debug::get()->add("FALL: " + std::to_string(falling_counter_ / 4));
Debug::get()->add("FALL: " + std::to_string(CLAMPED_INDEX));
#endif
}
}
// Comprueba si el jugador tiene suelo debajo de los pies
@@ -597,7 +610,8 @@ void Player::setState(PlayerState value) {
previous_state_ = state_;
state_ = value;
checkState();
// Llama a checkState con delta_time 0 porque esto es un cambio de estado inmediato
checkState(0.0F);
}
// Inicializa los sonidos de salto y caida