122 lines
2.3 KiB
C++
122 lines
2.3 KiB
C++
#include "ball.h"
|
|
#include "defines.h"
|
|
|
|
// Constructor
|
|
Ball::Ball(float x, float vx, float vy, Color color, Texture *texture)
|
|
{
|
|
x_ = x;
|
|
y_ = 0.0f;
|
|
w_ = BALL_SIZE;
|
|
h_ = BALL_SIZE;
|
|
vx_ = vx;
|
|
vy_ = vy;
|
|
sprite_ = new Sprite(texture);
|
|
sprite_->setPos({(int)x, (int)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;
|
|
}
|
|
|
|
// Destructor
|
|
Ball::~Ball()
|
|
{
|
|
if (sprite_)
|
|
{
|
|
delete sprite_;
|
|
}
|
|
}
|
|
|
|
// Actualiza la lógica de la clase
|
|
void Ball::update()
|
|
{
|
|
if (stopped_)
|
|
{
|
|
return;
|
|
}
|
|
|
|
// Aplica la gravedad a la velocidad
|
|
if (!on_floor_ && (y_ - SCREEN_HEIGHT) < BALL_SIZE * 2)
|
|
{
|
|
vy_ += gravity_force_;
|
|
}
|
|
|
|
// Actualiza la posición en función de la velocidad
|
|
x_ += vx_;
|
|
y_ += vy_;
|
|
|
|
// Comprueba las colisiones con el lateral izquierdo
|
|
if (x_ < 0)
|
|
{
|
|
x_ = 0;
|
|
vx_ = -vx_;
|
|
}
|
|
|
|
// Comprueba las colisiones con el lateral derecho
|
|
if (x_ + w_ > SCREEN_WIDTH)
|
|
{
|
|
x_ = SCREEN_WIDTH - w_;
|
|
vx_ = -vx_;
|
|
}
|
|
|
|
// Comprueba las colisiones con la parte superior
|
|
if (y_ < 0)
|
|
{
|
|
y_ = 0;
|
|
vy_ = -vy_;
|
|
}
|
|
|
|
// Comprueba las colisiones con la parte inferior
|
|
if (y_ + h_ > SCREEN_HEIGHT)
|
|
{
|
|
y_ = SCREEN_HEIGHT - 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({(int)x_, (int)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;
|
|
} |