110 lines
2.3 KiB
C++
110 lines
2.3 KiB
C++
#include "ball.h"
|
|
#include "defines.h"
|
|
|
|
// Constructor
|
|
Ball::Ball(float x, float vx, float vy, Color color, std::shared_ptr<Texture> texture)
|
|
{
|
|
pos_ = {x, 0.0f, BALL_SIZE, BALL_SIZE};
|
|
vx_ = vx;
|
|
vy_ = vy;
|
|
sprite_ = std::make_unique<Sprite>(texture);
|
|
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 (abs(vy_) < 0.1f)
|
|
{
|
|
vy_ = 0.0f;
|
|
on_floor_ = true;
|
|
}
|
|
}
|
|
|
|
// Aplica rozamiento al rodar por el suelo
|
|
if (on_floor_)
|
|
{
|
|
vx_ = vx_ * 0.97f;
|
|
if (abs(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;
|
|
} |