96 lines
1.7 KiB
C++
96 lines
1.7 KiB
C++
#include "ball.h"
|
|
|
|
// Constructor
|
|
Ball::Ball(int x, int y, int w, int h, int vx, int vy, Texture *texture)
|
|
{
|
|
this->x = x;
|
|
this->y = y;
|
|
this->w = w;
|
|
this->h = h;
|
|
this->vx = vx;
|
|
this->vy = vy;
|
|
sprite = new Sprite(texture);
|
|
sprite->setPos({x, y});
|
|
sprite->setSize(w, h);
|
|
sprite->setClip({0, 0, static_cast<float>(w), static_cast<float>(h)});
|
|
color = {(rand() % 192) + 32, (rand() % 192) + 32, (rand() % 192) + 32};
|
|
}
|
|
|
|
// Destructor
|
|
Ball::~Ball()
|
|
{
|
|
if (sprite)
|
|
{
|
|
delete sprite;
|
|
}
|
|
}
|
|
|
|
// Actualiza la lógica de la clase
|
|
void Ball::update()
|
|
{
|
|
const int luckyX = (rand() % 2) + 1;
|
|
const int luckyY = (rand() % 2) + 1;
|
|
|
|
bool collision = false;
|
|
|
|
// Actualiza la posición
|
|
x += vx;
|
|
y += vy;
|
|
|
|
// Comprueba las colisiones con el borde de la ventana
|
|
if (x < 0)
|
|
{
|
|
x = 0;
|
|
vx = luckyX;
|
|
collision = true;
|
|
}
|
|
|
|
if (x + w > DEMO_WIDTH)
|
|
{
|
|
x = DEMO_WIDTH - w;
|
|
vx = -luckyX;
|
|
collision = true;
|
|
}
|
|
|
|
if (y < 0)
|
|
{
|
|
y = 0;
|
|
vy = luckyY;
|
|
collision = true;
|
|
}
|
|
|
|
if (y + h > DEMO_HEIGHT)
|
|
{
|
|
y = DEMO_HEIGHT - h;
|
|
vy = -luckyY;
|
|
collision = true;
|
|
}
|
|
|
|
if (collision)
|
|
{
|
|
sprite->setAnimationSpeed((rand() % 15) + 5);
|
|
}
|
|
|
|
// Actualiza la posición del sprite
|
|
sprite->setPos({x, y});
|
|
sprite->update();
|
|
}
|
|
|
|
// Pinta la clase
|
|
void Ball::render()
|
|
{
|
|
sprite->setColor(color.r, color.g, color.b);
|
|
sprite->render();
|
|
}
|
|
|
|
// Establece el valor de la velocidad
|
|
void Ball::setVx(int value)
|
|
{
|
|
vx = value;
|
|
}
|
|
|
|
// Establece el valor de la velocidad
|
|
void Ball::setVy(int value)
|
|
{
|
|
vy = value;
|
|
} |