Files
demo5_sprites_bouncing/source/ball.cpp
2025-03-24 14:08:26 +01:00

113 lines
2.4 KiB
C++

#include "ball.h"
#include <stdlib.h> // for rand
#include <cmath> // for fabs
#include "defines.h" // for BALL_SIZE, Color, SCREEN_HEIGHT, GRAVITY_FORCE
class Texture;
// Constructor
Ball::Ball(float x, float vx, float vy, Color color, std::shared_ptr<Texture> texture)
: sprite_(std::make_unique<Sprite>(texture)),
pos_({x, 0.0f, BALL_SIZE, BALL_SIZE})
{
vx_ = vx;
vy_ = vy;
sprite_->setPos({pos_.x, pos_.y});
sprite_->setSize(BALL_SIZE, BALL_SIZE);
sprite_->setClip({0, 0, BALL_SIZE, BALL_SIZE});
color_ = color;
gravity_force_ = GRAVITY_FORCE;
on_floor_ = false;
stopped_ = false;
loss_ = ((rand() % 30) * 0.01f) + 0.6f;
}
// Actualiza la lógica de la clase
void Ball::update()
{
if (stopped_)
{
return;
}
// Aplica la gravedad a la velocidad
if (!on_floor_ && (pos_.y - SCREEN_HEIGHT) < BALL_SIZE * 2)
{
vy_ += gravity_force_;
}
// Actualiza la posición en función de la velocidad
pos_.x += vx_;
pos_.y += vy_;
// Comprueba las colisiones con el lateral izquierdo
if (pos_.x < 0)
{
pos_.x = 0;
vx_ = -vx_;
}
// Comprueba las colisiones con el lateral derecho
if (pos_.x + pos_.w > SCREEN_WIDTH)
{
pos_.x = SCREEN_WIDTH - pos_.w;
vx_ = -vx_;
}
// Comprueba las colisiones con la parte superior
if (pos_.y < 0)
{
pos_.y = 0;
vy_ = -vy_;
}
// Comprueba las colisiones con la parte inferior
if (pos_.y + pos_.h > SCREEN_HEIGHT)
{
pos_.y = SCREEN_HEIGHT - pos_.h;
vy_ = -vy_ * loss_;
if (std::fabs(vy_) < 0.1f)
{
vy_ = 0.0f;
on_floor_ = true;
}
}
// Aplica rozamiento al rodar por el suelo
if (on_floor_)
{
vx_ = vx_ * 0.97f;
if (std::fabs(vx_) < 0.1f)
{
vx_ = 0.0f;
stopped_ = true;
}
}
// Actualiza la posición del sprite
sprite_->setPos({pos_.x, pos_.y});
}
// Pinta la clase
void Ball::render()
{
sprite_->setColor(color_.r, color_.g, color_.b);
sprite_->render();
}
// Modifica la velocidad
void Ball::modVel(float vx, float vy)
{
if (stopped_)
{
vx_ = vx_ + vx;
}
vy_ = vy_ + vy;
on_floor_ = false;
stopped_ = false;
}
// Cambia la gravedad
void Ball::switchGravity()
{
gravity_force_ = gravity_force_ == 0.0f ? GRAVITY_FORCE : 0.0f;
}