Arreglades les herencies de Sprite

Abans de llevar mil coses que sobren i replantejar-se estes 4 classes
This commit is contained in:
2024-10-13 10:01:07 +02:00
parent 33ea8d90ca
commit b060f21696
17 changed files with 1204 additions and 284 deletions

View File

@@ -15,7 +15,9 @@ AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string
auto frame_height = 0;
auto max_tiles = 0;
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
#endif
std::ifstream file(file_path);
std::string line;
@@ -156,21 +158,20 @@ AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string
}
// Constructor
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, std::string file, std::vector<std::string> *buffer)
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file, std::vector<std::string> *buffer)
: MovingSprite(texture)
{
// Copia los punteros
setTexture(texture);
// Carga las animaciones
if (file != "")
{
AnimatedFile as = loadAnimationFromFile(texture, file);
// Copia los datos de las animaciones
for (auto animation : as.animations)
/*for (auto animation : as.animations)
{
animations_.push_back(animation);
}
}*/
std::copy(as.animations.begin(), as.animations.end(), std::back_inserter(animations_));
}
else if (buffer)
@@ -183,19 +184,14 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, std::string fil
}
// Constructor
AnimatedSprite::AnimatedSprite(AnimatedFile *animation)
AnimatedSprite::AnimatedSprite(const AnimatedFile *animation)
: MovingSprite(animation->texture)
{
// Copia los punteros
setTexture(animation->texture);
// Inicializa variables
current_animation_ = 0;
// Copia los datos de las animaciones
for (auto a : animation->animations)
{
animations_.push_back(a);
}
std::copy(animation->animations.begin(), animation->animations.end(), std::back_inserter(animations_));
}
// Destructor
@@ -205,11 +201,11 @@ AnimatedSprite::~AnimatedSprite()
}
// Obtiene el indice de la animación a partir del nombre
int AnimatedSprite::getIndex(std::string name)
int AnimatedSprite::getIndex(const std::string &name)
{
auto index = -1;
for (auto a : animations_)
for (const auto &a : animations_)
{
index++;
if (a.name == name)
@@ -226,7 +222,7 @@ int AnimatedSprite::getIndex(std::string name)
// Calcula el frame correspondiente a la animación
void AnimatedSprite::animate()
{
if (!enabled_ || animations_[current_animation_].speed == 0)
if (animations_[current_animation_].speed == 0)
{
return;
}
@@ -284,13 +280,13 @@ void AnimatedSprite::setCurrentFrame(int num)
}
// Establece el valor del contador
void AnimatedSprite::setAnimationCounter(std::string name, int num)
void AnimatedSprite::setAnimationCounter(const std::string &name, int num)
{
animations_[getIndex(name)].counter = num;
}
// Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(std::string name, int speed)
void AnimatedSprite::setAnimationSpeed(const std::string &name, int speed)
{
animations_[getIndex(name)].counter = speed;
}
@@ -302,7 +298,7 @@ void AnimatedSprite::setAnimationSpeed(int index, int speed)
}
// Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(std::string name, int loop)
void AnimatedSprite::setAnimationLoop(const std::string &name, int loop)
{
animations_[getIndex(name)].loop = loop;
}
@@ -314,7 +310,7 @@ void AnimatedSprite::setAnimationLoop(int index, int loop)
}
// Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(std::string name, bool value)
void AnimatedSprite::setAnimationCompleted(const std::string &name, bool value)
{
animations_[getIndex(name)].completed = value;
}
@@ -332,7 +328,7 @@ bool AnimatedSprite::animationIsCompleted()
}
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index)
SDL_Rect AnimatedSprite::getAnimationClip(const std::string &name, Uint8 index)
{
return animations_[getIndex(name)].frames[index];
}
@@ -484,13 +480,13 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
}
// Pone un valor por defecto
setRect({0, 0, frame_width, frame_height});
setPos((SDL_Rect){0, 0, frame_width, frame_height});
return success;
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(std::string name)
void AnimatedSprite::setCurrentAnimation(const std::string &name)
{
const auto new_animation = getIndex(name);
if (current_animation_ != new_animation)
@@ -518,11 +514,8 @@ void AnimatedSprite::setCurrentAnimation(int index)
// Actualiza las variables del objeto
void AnimatedSprite::update()
{
if (enabled_)
{
animate();
MovingSprite::update();
}
animate();
MovingSprite::update();
}
// Establece el rectangulo para un frame de una animación

View File

@@ -30,15 +30,15 @@ AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string
class AnimatedSprite : public MovingSprite
{
private:
protected:
// Variables
std::vector<Animation> animations_; // Vector con las diferentes animaciones
int current_animation_; // Animacion activa
public:
// Constructor
AnimatedSprite(std::shared_ptr<Texture> texture = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
AnimatedSprite(AnimatedFile *animation);
explicit AnimatedSprite(std::shared_ptr<Texture> texture = nullptr, const std::string &file = "", std::vector<std::string> *buffer = nullptr);
explicit AnimatedSprite(const AnimatedFile *animation);
// Destructor
~AnimatedSprite();
@@ -53,39 +53,39 @@ public:
void setCurrentFrame(int num);
// Establece el valor del contador
void setAnimationCounter(std::string name, int num);
void setAnimationCounter(const std::string &name, int num);
// Establece la velocidad de una animación
void setAnimationSpeed(std::string name, int speed);
void setAnimationSpeed(const std::string &name, int speed);
void setAnimationSpeed(int index, int speed);
// Establece el frame al que vuelve la animación al finalizar
void setAnimationLoop(std::string name, int loop);
void setAnimationLoop(const std::string &name, int loop);
void setAnimationLoop(int index, int loop);
// Establece el valor de la variable
void setAnimationCompleted(std::string name, bool value);
void setAnimationCompleted(const std::string &name, bool value);
void setAnimationCompleted(int index, bool value);
// Comprueba si ha terminado la animación
bool animationIsCompleted();
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect getAnimationClip(std::string name = "default", Uint8 index = 0);
SDL_Rect getAnimationClip(const std::string &name = "default", Uint8 index = 0);
SDL_Rect getAnimationClip(int indexA = 0, Uint8 indexF = 0);
// Obtiene el indice de la animación a partir del nombre
int getIndex(std::string name);
int getIndex(const std::string &name);
// Carga la animación desde un vector
bool loadFromVector(std::vector<std::string> *source);
// Establece la animacion actual
void setCurrentAnimation(std::string name = "default");
void setCurrentAnimation(const std::string &name = "default");
void setCurrentAnimation(int index = 0);
// Actualiza las variables del objeto
void update();
void update() override;
// OLD - Establece el rectangulo para un frame de una animación
void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h);

View File

@@ -5,35 +5,35 @@
#include <iostream> // for basic_ostream, operator<<, cout, endl
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Asset *Asset::asset = nullptr;
Asset *Asset::asset_ = nullptr;
// [SINGLETON] Crearemos el objeto asset con esta función estática
void Asset::init(std::string executable_path)
void Asset::init(const std::string &executable_path)
{
Asset::asset = new Asset(executable_path);
Asset::asset_ = new Asset(executable_path);
}
// [SINGLETON] Destruiremos el objeto asset con esta función estática
void Asset::destroy()
{
delete Asset::asset;
delete Asset::asset_;
}
// [SINGLETON] Con este método obtenemos el objeto asset y podemos trabajar con él
Asset *Asset::get()
{
return Asset::asset;
return Asset::asset_;
}
// Constructor
Asset::Asset(std::string executable_path)
Asset::Asset(const std::string &executable_path)
{
executable_path_ = executable_path.substr(0, executable_path.find_last_of("\\/"));
longest_name_ = 0;
}
// Añade un elemento a la lista
void Asset::add(std::string file, AssetType type, bool required, bool absolute)
void Asset::add(const std::string &file, AssetType type, bool required, bool absolute)
{
AssetItem ai;
ai.file = absolute ? file : executable_path_ + file;
@@ -46,9 +46,9 @@ void Asset::add(std::string file, AssetType type, bool required, bool absolute)
}
// Devuelve el fichero de un elemento de la lista a partir de una cadena
std::string Asset::get(std::string text) const
std::string Asset::get(const std::string &text) const
{
for (auto f : file_list_)
for (const auto &f : file_list_)
{
const size_t last_index = f.file.find_last_of("/") + 1;
const std::string file = f.file.substr(last_index, std::string::npos);
@@ -83,7 +83,7 @@ bool Asset::check() const
// Comprueba si hay ficheros de ese tipo
bool any = false;
for (auto f : file_list_)
for (const auto &f : file_list_)
{
if (f.required && f.type == static_cast<AssetType>(type))
{
@@ -98,7 +98,7 @@ bool Asset::check() const
std::cout << "\n>> " << getTypeName(static_cast<AssetType>(type)).c_str() << " FILES" << std::endl;
#endif
for (auto f : file_list_)
for (const auto &f : file_list_)
{
if (f.required && f.type == static_cast<AssetType>(type))
{
@@ -117,29 +117,27 @@ bool Asset::check() const
}
// Comprueba que existe un fichero
bool Asset::checkFile(std::string path) const
bool Asset::checkFile(const std::string &path) const
{
bool success = false;
std::string result = "ERROR";
auto success = false;
// Comprueba si existe el fichero
const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
SDL_RWops *file = SDL_RWFromFile(path.c_str(), "rb");
auto file = SDL_RWFromFile(path.c_str(), "rb");
if (file != nullptr)
if (file)
{
result = "OK";
success = true;
SDL_RWclose(file);
}
#ifdef VERBOSE
const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
std::cout.setf(std::ios::left, std::ios::adjustfield);
std::cout << "Checking file: ";
std::cout.width(longest_name_ + 2);
std::cout.fill('.');
std::cout << file_name + " ";
std::cout << " [" + result + "]" << std::endl;
std::cout << file_name;
std::cout << (success ? " [OK]" : " [ERROR]") << std::endl;
#endif
return success;

View File

@@ -1,7 +1,7 @@
#pragma once
#include <string> // for string, basic_string
#include <vector> // for vector
#include <string> // for string, basic_string
#include <vector> // for vector
enum class AssetType : int
{
@@ -22,7 +22,7 @@ class Asset
{
private:
// [SINGLETON] Objeto asset privado para Don Melitón
static Asset *asset;
static Asset *asset_;
// Estructura para definir un item
struct AssetItem
@@ -34,25 +34,25 @@ private:
};
// Variables
int longest_name_; // Contiene la longitud del nombre de fichero mas largo
int longest_name_; // Contiene la longitud del nombre de fichero mas largo
std::vector<AssetItem> file_list_; // Listado con todas las rutas a los ficheros
std::string executable_path_; // Ruta al ejecutable
std::string executable_path_; // Ruta al ejecutable
// Comprueba que existe un fichero
bool checkFile(std::string executable_path) const;
bool checkFile(const std::string &path) const;
// Devuelve el nombre del tipo de recurso
std::string getTypeName(AssetType type) const;
// Constructor
Asset(std::string path);
explicit Asset(const std::string &executable_path);
// Destructor
~Asset() = default;
public:
// [SINGLETON] Crearemos el objeto screen con esta función estática
static void init(std::string path);
static void init(const std::string &executable_path);
// [SINGLETON] Destruiremos el objeto screen con esta función estática
static void destroy();
@@ -61,10 +61,10 @@ public:
static Asset *get();
// Añade un elemento a la lista
void add(std::string file, AssetType type, bool required = true, bool absolute = false);
void add(const std::string &file, AssetType type, bool required = true, bool absolute = false);
// Devuelve un elemento de la lista a partir de una cadena
std::string get(std::string text) const;
std::string get(const std::string &text) const;
// Comprueba que existen todos los elementos
bool check() const;

View File

@@ -8,15 +8,14 @@
// Constructor
Background::Background(SDL_Renderer *renderer)
: renderer_(renderer)
{
// Carga las texturas
buildings_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_buildings.png"));
top_clouds_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds1.png"));
bottom_clouds_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds2.png"));
grass_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_grass.png"));
gradients_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_sky_colors.png"));
: renderer_(renderer),
buildings_texture_(std::make_shared<Texture>(renderer, Asset::get()->get("game_buildings.png"))),
top_clouds_texture_(std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds1.png"))),
bottom_clouds_texture_(std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds2.png"))),
grass_texture_(std::make_shared<Texture>(renderer, Asset::get()->get("game_grass.png"))),
gradients_texture_(std::make_shared<Texture>(renderer, Asset::get()->get("game_sky_colors.png")))
{
// Inicializa variables
gradient_number_ = 0;
alpha_ = 0;

View File

@@ -107,7 +107,7 @@ private:
public:
// Constructor
Background(SDL_Renderer *renderer);
explicit Background(SDL_Renderer *renderer);
// Destructor
~Background();

View File

@@ -323,7 +323,7 @@ void Balloon::render()
if (kind_ == POWER_BALL && !isBeingCreated())
{
auto sp = std::make_unique<Sprite>(sprite_->getRect(), sprite_->getTexture());
auto sp = std::make_unique<Sprite>(sprite_->getPos(), sprite_->getTexture());
sp->setSpriteClip(BALLOON_WIDTH_4, 0, BALLOON_WIDTH_4, BALLOON_WIDTH_4);
sp->render();
}

View File

@@ -32,7 +32,6 @@ Logo::Logo()
dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2;
since_sprite_->setPosY(dest_.y + jail_texture_->getHeight() + 5);
since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight());
since_sprite_->setEnabled(false);
since_texture_->setColor(0x00, 0x00, 0x00); // Esto en linux no hace nada ??
// Crea los sprites de cada linea
@@ -192,12 +191,6 @@ void Logo::update()
{
section::name = section::Name::INTRO;
}
// Comprueba si se ha de mostrar el sprite
else if (counter_ == SHOW_SINCE_SPRITE_COUNTER_MARK)
{
since_sprite_->setEnabled(true);
}
}
}
@@ -215,7 +208,11 @@ void Logo::render()
{
sprite->render();
}
since_sprite_->render();
if (counter_ >= SHOW_SINCE_SPRITE_COUNTER_MARK)
{
since_sprite_->render();
}
// Vuelca el contenido del renderizador en pantalla
Screen::get()->blit();

View File

@@ -3,31 +3,39 @@
// Constructor
MovingSprite::MovingSprite(float x, float y, int w, int h, float vx, float vy, float ax, float ay, std::shared_ptr<Texture> texture)
: Sprite((int)x, (int)y, w, h, texture), x_(x), y_(y), vx_(vx), vy_(vy), ax_(ax), ay_(ay)
: Sprite((int)x, (int)y, w, h, texture),
x_(x),
y_(y),
vx_(vx),
vy_(vy),
ax_(ax),
ay_(ay)
{
// Establece el zoom W,H del sprite
zoomW_ = 1;
zoomH_ = 1;
// Establece el angulo con el que se dibujará
angle_ = (double)0;
zoom_w_ = 1;
zoom_h_ = 1;
// Establece los valores de rotacion
rotateEnabled_ = false;
rotateSpeed_ = 0;
rotateAmount_ = (double)0;
rotate_.enabled = false;
rotate_.speed = 0;
rotate_.angle = 0.0f;
rotate_.amount = 0.0f;
rotate_.center = nullptr;
// Contador interno
counter_ = 0;
// Establece el rectangulo de donde coger la imagen
spriteClip_ = {0, 0, w_, h_};
// Establece el centro de rotación
center_ = nullptr;
sprite_clip_ = (SDL_Rect){0, 0, w, h};
// Establece el tipo de volteado
currentFlip_ = SDL_FLIP_NONE;
flip_ = SDL_FLIP_NONE;
};
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
: Sprite(texture)
{
clear();
};
// Reinicia todas las variables
@@ -42,17 +50,21 @@ void MovingSprite::clear()
ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
zoomW_ = 1.0f; // Zoom aplicado a la anchura
zoomH_ = 1.0f; // Zoom aplicado a la altura
zoom_w_ = 1.0f; // Zoom aplicado a la anchura
zoom_h_ = 1.0f; // Zoom aplicado a la altura
angle_ = 0.0; // Angulo para dibujarlo
rotateEnabled_ = false; // Indica si ha de rotar
center_ = nullptr; // Centro de rotación
rotateSpeed_ = 0; // Velocidad de giro
rotateAmount_ = 0.0; // Cantidad de grados a girar en cada iteración
counter_ = 0; // Contador interno
rotate_.enabled = false; // Indica si ha de rotar
rotate_.speed = 0; // Velocidad de giro
rotate_.angle = 0.0f; // Angulo para dibujarlo
rotate_.amount = 0.0f; // Cantidad de grados a girar en cada iteración
rotate_.center = nullptr; // Centro de rotación
currentFlip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
counter_ = 0; // Contador interno
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
setPos((SDL_Rect){0, 0, 0, 0});
setSpriteClip((SDL_Rect){0, 0, 0, 0});
}
// Mueve el sprite
@@ -68,10 +80,7 @@ void MovingSprite::move()
// Muestra el sprite por pantalla
void MovingSprite::render()
{
if (enabled_)
{
texture_->render((int)x_, (int)y_, &spriteClip_, zoomW_, zoomH_, angle_, center_, currentFlip_);
}
texture_->render((int)x_, (int)y_, &sprite_clip_, zoom_w_, zoom_h_, (double)rotate_.angle, rotate_.center, flip_);
}
// Obtiene el valor de la variable
@@ -113,28 +122,28 @@ float MovingSprite::getAccelY() const
// Obtiene el valor de la variable
float MovingSprite::getZoomW() const
{
return zoomW_;
return zoom_w_;
}
// Obtiene el valor de la variable
float MovingSprite::getZoomH() const
{
return zoomH_;
return zoom_h_;
}
// Obtiene el valor de la variable
double MovingSprite::getAngle() const
float MovingSprite::getAngle() const
{
return angle_;
return rotate_.angle;
}
// Establece la posición y_ el tamaño del objeto
void MovingSprite::setRect(SDL_Rect rect)
void MovingSprite::setPos(SDL_Rect rect)
{
x_ = (float)rect.x;
y_ = (float)rect.y;
w_ = rect.w;
h_ = rect.h;
pos_ = rect;
}
// Establece el valor de las variables
@@ -142,18 +151,23 @@ void MovingSprite::setPos(float x, float y)
{
x_ = x;
y_ = y;
pos_.x = (int)x;
pos_.y = (int)y;
}
// Establece el valor de la variable
void MovingSprite::setPosX(float value)
{
x_ = value;
pos_.x = (int)x_;
}
// Establece el valor de la variable
void MovingSprite::setPosY(float value)
{
y_ = value;
pos_.y = (int)y_;
}
// Establece el valor de la variable
@@ -183,53 +197,53 @@ void MovingSprite::setAccelY(float value)
// Establece el valor de la variable
void MovingSprite::setZoomW(float value)
{
zoomW_ = value;
zoom_w_ = value;
}
// Establece el valor de la variable
void MovingSprite::setZoomH(float value)
{
zoomH_ = value;
zoom_h_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAngle(double value)
{
angle_ = value;
rotate_.angle = value;
}
// Incrementa el valor de la variable
void MovingSprite::incAngle(double value)
{
angle_ += value;
rotate_.angle += value;
}
// Decrementa el valor de la variable
void MovingSprite::decAngle(double value)
{
angle_ -= value;
rotate_.angle -= value;
}
// Obtiene el valor de la variable
bool MovingSprite::getRotate() const
{
return rotateEnabled_;
return rotate_.enabled;
}
// Obtiene el valor de la variable
Uint16 MovingSprite::getRotateSpeed() const
{
return rotateSpeed_;
return rotate_.speed;
}
// Establece la rotacion
void MovingSprite::rotate()
{
if (rotateEnabled_)
if (rotate_.enabled)
{
if (counter_ % rotateSpeed_ == 0)
if (counter_ % rotate_.speed == 0)
{
incAngle(rotateAmount_);
incAngle(rotate_.amount);
}
}
}
@@ -237,65 +251,62 @@ void MovingSprite::rotate()
// Establece el valor de la variable
void MovingSprite::setRotate(bool value)
{
rotateEnabled_ = value;
rotate_.enabled = value;
}
// Establece el valor de la variable
void MovingSprite::setRotateSpeed(int value)
{
rotateSpeed_ = (value < 1) ? 1 : value;
rotate_.speed = (value < 1) ? 1 : value;
}
// Establece el valor de la variable
void MovingSprite::setRotateAmount(double value)
{
rotateAmount_ = value;
rotate_.amount = value;
}
// Establece el valor de la variable
void MovingSprite::disableRotate()
{
rotateEnabled_ = false;
angle_ = (double)0;
rotate_.enabled = false;
rotate_.angle = 0.0f;
}
// Actualiza las variables internas del objeto
void MovingSprite::update()
{
if (enabled_)
{
move();
rotate();
++counter_ %= 60000;
}
move();
rotate();
++counter_ %= 60000;
}
// Cambia el sentido de la rotación
void MovingSprite::switchRotate()
{
rotateAmount_ *= -1;
rotate_.amount *= -1;
}
// Establece el valor de la variable
void MovingSprite::setFlip(SDL_RendererFlip flip)
{
currentFlip_ = flip;
flip_ = flip;
}
// Gira el sprite horizontalmente
void MovingSprite::flip()
{
currentFlip_ = (currentFlip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
}
// Obtiene el valor de la variable
SDL_RendererFlip MovingSprite::getFlip()
{
return currentFlip_;
return flip_;
}
// Devuelve el rectangulo donde está el sprite
SDL_Rect MovingSprite::getRect()
SDL_Rect MovingSprite::getPos() const
{
return (SDL_Rect){(int)x_, (int)y_, w_, h_};
return (SDL_Rect){(int)x_, (int)y_, pos_.w, pos_.h};
}

View File

@@ -1,16 +1,25 @@
#pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point
#include <SDL2/SDL_render.h> // for SDL_RendererFlip
#include <SDL2/SDL_stdinc.h> // for Uint16
#include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point
#include <SDL2/SDL_render.h> // for SDL_RendererFlip
#include <SDL2/SDL_stdinc.h> // for Uint16
#include <memory>
#include "sprite.h" // for Sprite
#include "sprite.h" // for Sprite
#include "texture.h"
// Clase MovingSprite. Añade posicion y velocidad en punto flotante
class MovingSprite : public Sprite
{
protected:
struct Rotate
{
bool enabled; // Indica si ha de rotar
int speed; // Velocidad de giro
float angle; // Angulo para dibujarlo
float amount; // Cantidad de grados a girar en cada iteración
SDL_Point *center; // Centro de rotación
};
float x_; // Posición en el eje X
float y_; // Posición en el eje Y
@@ -20,20 +29,17 @@ protected:
float ax_; // Aceleración en el eje X. Variación de la velocidad
float ay_; // Aceleración en el eje Y. Variación de la velocidad
float zoomW_; // Zoom aplicado a la anchura
float zoomH_; // Zoom aplicado a la altura
float zoom_w_; // Zoom aplicado a la anchura
float zoom_h_; // Zoom aplicado a la altura
double angle_; // Angulo para dibujarlo
bool rotateEnabled_; // Indica si ha de rotar
int rotateSpeed_; // Velocidad de giro
double rotateAmount_; // Cantidad de grados a girar en cada iteración
int counter_; // Contador interno
SDL_Point *center_; // Centro de rotación
SDL_RendererFlip currentFlip_; // Indica como se voltea el sprite
int counter_; // Contador interno
Rotate rotate_; // Variables usada para controlar la rotación del sprite
SDL_RendererFlip flip_; // Indica como se voltea el sprite
public:
// Constructor
MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, std::shared_ptr<Texture> texture = nullptr);
explicit MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, std::shared_ptr<Texture> texture = nullptr);
explicit MovingSprite(std::shared_ptr<Texture> texture = nullptr);
// Mueve el sprite
void move();
@@ -42,13 +48,13 @@ public:
void rotate();
// Actualiza las variables internas del objeto
void update();
virtual void update();
// Reinicia todas las variables
void clear();
// Muestra el sprite por pantalla
void render();
void render() override;
// Obten el valor de la variable
float getPosX() const;
@@ -67,16 +73,17 @@ public:
float getZoomH() const;
// Obten el valor de la variable
double getAngle() const;
float getAngle() const;
bool getRotate() const;
Uint16 getRotateSpeed() const;
// Establece la posición y el tamaño del objeto
void setRect(SDL_Rect rect);
// Establece el valor de las variables
// Establece la posición del objeto
void setPos(SDL_Rect rect) override;
void setPos(float x, float y);
// Devuelve el rectangulo donde está el sprite
SDL_Rect getPos() const override;
// Establece el valor de la variable
void setPosX(float value);
void setPosY(float value);
@@ -118,6 +125,5 @@ public:
// Obtiene el valor de la variable
SDL_RendererFlip getFlip();
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect();
};

View File

@@ -4,20 +4,18 @@ class Texture;
// Constructor
SmartSprite::SmartSprite(std::shared_ptr<Texture> texture)
: AnimatedSprite(texture)
{
// Copia punteros
setTexture(texture);
init();
}
// Inicializa el objeto
void SmartSprite::init()
{
finishedCounter_ = 0;
onDestination_ = false;
destX_ = 0;
destY_ = 0;
finished_counter_ = 0;
on_destination_ = false;
dest_x_ = 0;
dest_y_ = 0;
finished_ = false;
enabled_ = false;
}
@@ -36,31 +34,31 @@ void SmartSprite::update()
// Establece el valor de la variable
void SmartSprite::setFinishedCounter(int value)
{
finishedCounter_ = value;
finished_counter_ = value;
}
// Establece el valor de la variable
void SmartSprite::setDestX(int x)
{
destX_ = x;
dest_x_ = x;
}
// Establece el valor de la variable
void SmartSprite::setDestY(int y)
{
destY_ = y;
dest_y_ = y;
}
// Obtiene el valor de la variable
int SmartSprite::getDestX() const
{
return destX_;
return dest_x_;
}
// Obtiene el valor de la variable
int SmartSprite::getDestY() const
{
return destY_;
return dest_y_;
}
// Comprueba el movimiento
@@ -70,10 +68,10 @@ void SmartSprite::checkMove()
if (getAccelX() > 0 || getVelX() > 0)
{
// Comprueba si ha llegado al destino
if (getPosX() > destX_)
if (getPosX() > dest_x_)
{
// Lo coloca en posición
setPosX(destX_);
setPosX(dest_x_);
// Lo detiene
setVelX(0.0f);
@@ -84,10 +82,10 @@ void SmartSprite::checkMove()
else if (getAccelX() < 0 || getVelX() < 0)
{
// Comprueba si ha llegado al destino
if (getPosX() < destX_)
if (getPosX() < dest_x_)
{
// Lo coloca en posición
setPosX(destX_);
setPosX(dest_x_);
// Lo detiene
setVelX(0.0f);
@@ -99,10 +97,10 @@ void SmartSprite::checkMove()
if (getAccelY() > 0 || getVelY() > 0)
{
// Comprueba si ha llegado al destino
if (getPosY() > destY_)
if (getPosY() > dest_y_)
{
// Lo coloca en posición
setPosY(destY_);
setPosY(dest_y_);
// Lo detiene
setVelY(0.0f);
@@ -113,10 +111,10 @@ void SmartSprite::checkMove()
else if (getAccelY() < 0 || getVelY() < 0)
{
// Comprueba si ha llegado al destino
if (getPosY() < destY_)
if (getPosY() < dest_y_)
{
// Lo coloca en posición
setPosY(destY_);
setPosY(dest_y_);
// Lo detiene
setVelY(0.0f);
@@ -129,17 +127,17 @@ void SmartSprite::checkMove()
void SmartSprite::checkFinished()
{
// Comprueba si ha llegado a su destino
onDestination_ = (getPosX() == destX_ && getPosY() == destY_) ? true : false;
on_destination_ = (getPosX() == dest_x_ && getPosY() == dest_y_) ? true : false;
if (onDestination_)
if (on_destination_)
{
if (finishedCounter_ == 0)
if (finished_counter_ == 0)
{
finished_ = true;
}
else
{
--finishedCounter_;
--finished_counter_;
}
}
}
@@ -147,11 +145,16 @@ void SmartSprite::checkFinished()
// Obtiene el valor de la variable
bool SmartSprite::isOnDestination() const
{
return onDestination_;
return on_destination_;
}
// Obtiene el valor de la variable
bool SmartSprite::hasFinished() const
{
return finished_;
}
void SmartSprite::setEnabled(bool value)
{
enabled_ = value;
}

View File

@@ -9,11 +9,12 @@ class SmartSprite : public AnimatedSprite
{
private:
// Variables
bool onDestination_; // Indica si está en el destino
int destX_; // Posicion de destino en el eje X
int destY_; // Posicion de destino en el eje Y
int finishedCounter_; // Contador para deshabilitarlo
bool finished_; // Indica si ya ha terminado
bool on_destination_; // Indica si está en el destino
int dest_x_; // Posicion de destino en el eje X
int dest_y_; // Posicion de destino en el eje Y
int finished_counter_; // Contador para deshabilitarlo
bool finished_; // Indica si ya ha terminado
bool enabled_; // Indica si el objeto está habilitado
// Comprueba el movimiento
void checkMove();
@@ -23,7 +24,7 @@ private:
public:
// Constructor
SmartSprite(std::shared_ptr<Texture> texture);
explicit SmartSprite(std::shared_ptr<Texture> texture);
// Destructor
~SmartSprite() = default;
@@ -32,7 +33,7 @@ public:
void init();
// Actualiza la posición y comprueba si ha llegado a su destino
void update();
void update() override;
// Establece el valor de la variable
void setFinishedCounter(int value);
@@ -54,4 +55,6 @@ public:
// Obtiene el valor de la variable
bool hasFinished() const;
void setEnabled(bool value);
};

View File

@@ -2,121 +2,108 @@
// Constructor
Sprite::Sprite(int x, int y, int w, int h, std::shared_ptr<Texture> texture)
: x_(x), y_(y), w_(w), h_(h), texture_(texture)
{
// Establece el rectangulo de donde coger la imagen
spriteClip_ = {0, 0, w, h};
// Inicializa variables
enabled_ = true;
}
: texture_(texture),
pos_((SDL_Rect){x, y, w, h}),
sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(SDL_Rect rect, std::shared_ptr<Texture> texture)
: x_(rect.x), y_(rect.y), w_(rect.w), h_(rect.h), texture_(texture)
{
// Establece el rectangulo de donde coger la imagen
spriteClip_ = {0, 0, w_, h_};
: texture_(texture),
pos_(rect),
sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
// Inicializa variables
enabled_ = true;
}
Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(texture) {}
// Muestra el sprite por pantalla
void Sprite::render()
{
if (enabled_)
{
texture_->render(x_, y_, &spriteClip_);
}
texture_->render(pos_.x, pos_.y, &sprite_clip_);
}
// Obten el valor de la variable
int Sprite::getPosX() const
{
return x_;
return pos_.x;
}
// Obten el valor de la variable
int Sprite::getPosY() const
{
return y_;
return pos_.y;
}
// Obten el valor de la variable
int Sprite::getWidth() const
{
return w_;
return pos_.w;
}
// Obten el valor de la variable
int Sprite::getHeight() const
{
return h_;
return pos_.h;
}
// Establece la posición del objeto
void Sprite::setPos(int x, int y)
{
x_ = x;
y_ = y;
pos_.x = x;
pos_.y = y;
}
// Establece la posición del objeto
void Sprite::setPos(SDL_Point p)
{
x_ = p.x;
y_ = p.y;
pos_.x = p.x;
pos_.y = p.y;
}
// Establece la posición del objeto
void Sprite::setPos(SDL_Rect r)
{
x_ = r.x;
y_ = r.y;
w_ = r.w;
h_ = r.h;
pos_ = r;
}
// Establece el valor de la variable
void Sprite::setPosX(int x)
{
x_ = x;
pos_.x = x;
}
// Establece el valor de la variable
void Sprite::setPosY(int y)
{
y_ = y;
pos_.y = y;
}
// Establece el valor de la variable
void Sprite::setWidth(int w)
{
w_ = w;
pos_.w = w;
}
// Establece el valor de la variable
void Sprite::setHeight(int h)
{
h_ = h;
pos_.h = h;
}
// Obten el valor de la variable
SDL_Rect Sprite::getSpriteClip() const
{
return spriteClip_;
return sprite_clip_;
}
// Establece el valor de la variable
void Sprite::setSpriteClip(SDL_Rect rect)
{
spriteClip_ = rect;
sprite_clip_ = rect;
}
// Establece el valor de la variable
void Sprite::setSpriteClip(int x, int y, int w, int h)
{
spriteClip_ = (SDL_Rect){x, y, w, h};
sprite_clip_ = (SDL_Rect){x, y, w, h};
}
// Obten el valor de la variable
@@ -131,32 +118,20 @@ void Sprite::setTexture(std::shared_ptr<Texture> texture)
texture_ = texture;
}
// Establece el valor de la variable
void Sprite::setEnabled(bool value)
{
enabled_ = value;
}
// Comprueba si el objeto está habilitado
bool Sprite::isEnabled() const
{
return enabled_;
}
// Devuelve el rectangulo donde está el sprite
SDL_Rect Sprite::getRect() const
SDL_Rect Sprite::getPos() const
{
return (SDL_Rect){x_, y_, w_, h_};
return pos_;
}
// Incrementa el valor de la variable
void Sprite::incPosX(int value)
{
x_ += value;
pos_.x += value;
}
// Incrementa el valor de la variable
void Sprite::incPosY(int value)
{
y_ += value;
pos_.y += value;
}

View File

@@ -8,26 +8,22 @@
class Sprite
{
protected:
int x_; // Posición en el eje X donde dibujar el sprite
int y_; // Posición en el eje Y donde dibujar el sprite
int w_; // Ancho del sprite
int h_; // Alto del sprite
// Variables
std::shared_ptr<Texture> texture_; // Textura donde estan todos los dibujos del sprite
SDL_Rect spriteClip_; // Rectangulo de origen de la textura que se dibujará en pantalla
bool enabled_; // Indica si el sprite esta habilitado
SDL_Rect pos_; // Posición y tamaño donde dibujar el sprite
SDL_Rect sprite_clip_; // Rectangulo de origen de la textura que se dibujará en pantalla
public:
// Constructor
Sprite(int x = 0, int y = 0, int w = 0, int h = 0, std::shared_ptr<Texture> texture = nullptr);
Sprite(SDL_Rect rect, std::shared_ptr<Texture> texture = nullptr);
explicit Sprite(int x = 0, int y = 0, int w = 0, int h = 0, std::shared_ptr<Texture> texture = nullptr);
explicit Sprite(SDL_Rect rect, std::shared_ptr<Texture> texture = nullptr);
explicit Sprite(std::shared_ptr<Texture> texture = nullptr);
// Destructor
~Sprite() = default;
// Muestra el sprite por pantalla
void render();
virtual void render();
// Obten el valor de la variable
int getPosX() const;
@@ -35,20 +31,20 @@ public:
int getWidth() const;
int getHeight() const;
// Establece la posición del objeto
void setPos(int x, int y);
void setPos(SDL_Point p);
void setPos(SDL_Rect r);
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect() const;
virtual SDL_Rect getPos() const;
// Establece el valor de la variable
void setPosX(int x);
void setPosY(int y);
void setWidth(int w);
void setHeight(int h);
// Establece la posición del objeto
void setPos(int x, int y);
void setPos(SDL_Point p);
virtual void setPos(SDL_Rect r);
// Incrementa el valor de la variable
void incPosX(int value);
void incPosY(int value);
@@ -65,11 +61,4 @@ public:
// Establece el valor de la variable
void setTexture(std::shared_ptr<Texture> texture);
// Establece el valor de la variable
void setEnabled(bool value);
// Comprueba si el objeto está habilitado
bool isEnabled() const;
};

View File

@@ -49,7 +49,7 @@ private:
public:
// Constructor
Texture(SDL_Renderer *renderer, std::string path = "");
explicit Texture(SDL_Renderer *renderer, std::string path = "");
// Destructor
~Texture();