Files
demo4_sprites/source/ball.cpp
2024-08-21 07:35:52 +02:00

97 lines
1.6 KiB
C++

#include "ball.h"
#include "defines.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, 24, 24});
color = {255, 255, 255};
}
// 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 > SCREEN_WIDTH)
{
x = SCREEN_WIDTH - w;
vx = -luckyX;
collision = true;
}
if (y < 0)
{
y = 0;
vy = luckyY;
collision = true;
}
if (y + h > SCREEN_HEIGHT)
{
y = SCREEN_HEIGHT - h;
vy = -luckyY;
collision = true;
}
if (collision)
{
color = {rand() % 255, rand() % 255, rand() % 255};
}
// 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;
}