Compare commits
7 Commits
22ddfcd153
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 0a3fcd91d7 | |||
| 38f23c83c3 | |||
| 857a0c05f1 | |||
| a7c0b7d8c6 | |||
| 45b763791a | |||
| 57db69d2a4 | |||
| 1eab622ba2 |
107
.gitignore
vendored
107
.gitignore
vendored
@@ -1,2 +1,107 @@
|
||||
demo4_sprites
|
||||
build/
|
||||
|
||||
# ---> C++
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.dll
|
||||
*.out
|
||||
*.app
|
||||
|
||||
# ---> macOS
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# ---> Windows
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
Thumbs.db:encryptable
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
[Dd]esktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# ---> Linux
|
||||
*~
|
||||
|
||||
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||
.fuse_hidden*
|
||||
|
||||
# KDE directory preferences
|
||||
.directory
|
||||
|
||||
# Linux trash folder which might appear on any partition or disk
|
||||
.Trash-*
|
||||
|
||||
# .nfs files are created when an open file is removed but is still being accessed
|
||||
.nfs*
|
||||
|
||||
|
||||
49
CMakeLists.txt
Normal file
49
CMakeLists.txt
Normal file
@@ -0,0 +1,49 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(demo4_sprites)
|
||||
|
||||
# Establecer el estándar de C++
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# Opciones comunes de compilación
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Os -ffunction-sections -fdata-sections")
|
||||
|
||||
# Buscar SDL3 automáticamente
|
||||
find_package(SDL3 REQUIRED)
|
||||
|
||||
# Si no se encuentra SDL3, generar un error
|
||||
if (NOT SDL3_FOUND)
|
||||
message(FATAL_ERROR "SDL3 no encontrado. Por favor, verifica su instalación.")
|
||||
endif()
|
||||
|
||||
# Archivos fuente
|
||||
file(GLOB SOURCE_FILES source/*.cpp)
|
||||
|
||||
# Comprobar si se encontraron archivos fuente
|
||||
if(NOT SOURCE_FILES)
|
||||
message(FATAL_ERROR "No se encontraron archivos fuente en el directorio 'source/'. Verifica la ruta.")
|
||||
endif()
|
||||
|
||||
# Detectar la plataforma y configuraciones específicas
|
||||
if(WIN32)
|
||||
set(PLATFORM windows)
|
||||
set(LINK_LIBS ${SDL3_LIBRARIES} mingw32 ws2_32)
|
||||
elseif(UNIX AND NOT APPLE)
|
||||
set(PLATFORM linux)
|
||||
set(LINK_LIBS ${SDL3_LIBRARIES})
|
||||
elseif(APPLE)
|
||||
set(PLATFORM macos)
|
||||
set(LINK_LIBS ${SDL3_LIBRARIES})
|
||||
endif()
|
||||
|
||||
# Incluir directorios de SDL3
|
||||
include_directories(${SDL3_INCLUDE_DIRS})
|
||||
|
||||
# Añadir el ejecutable reutilizando el nombre del proyecto
|
||||
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
|
||||
|
||||
# Especificar la ubicación del ejecutable (en la raíz del proyecto)
|
||||
set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR})
|
||||
|
||||
# Enlazar las bibliotecas necesarias
|
||||
target_link_libraries(${PROJECT_NAME} ${LINK_LIBS})
|
||||
25
Makefile
25
Makefile
@@ -1,11 +1,20 @@
|
||||
source := source/*.cpp
|
||||
executable_name := demo_pelotas1
|
||||
# Variables comunes
|
||||
SOURCE := source/*.cpp
|
||||
EXECUTABLE_NAME := demo4_sprites
|
||||
CXXFLAGS := -std=c++20 -Wall -Os -ffunction-sections -fdata-sections # Opciones comunes de compilación
|
||||
LDFLAGS := -lSDL3 # Flags de enlace comunes
|
||||
OUTPUT_EXT :=
|
||||
|
||||
windows:
|
||||
g++ $(source) -std=c++11 -Wall -lmingw32 -lws2_32 -lSDL2main -lSDL2 -o $(executable_name).exe
|
||||
# Detectar plataforma y configurar
|
||||
ifeq ($(OS),Windows_NT)
|
||||
LDFLAGS += -lmingw32 -lws2_32
|
||||
OUTPUT_EXT := .exe
|
||||
endif
|
||||
|
||||
linux:
|
||||
g++ $(source) -std=c++11 -Wall -lSDL2 -o $(executable_name)
|
||||
# Regla principal: compilar el ejecutable
|
||||
all:
|
||||
$(CXX) $(SOURCE) $(CXXFLAGS) $(LDFLAGS) -o $(EXECUTABLE_NAME)$(OUTPUT_EXT)
|
||||
|
||||
macos:
|
||||
g++ $(source) -std=c++11 -Wall -lSDL2 -o $(executable_name)
|
||||
# Regla para limpiar archivos generados
|
||||
clean:
|
||||
rm -f $(EXECUTABLE_NAME)$(OUTPUT_EXT)
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 542 B |
BIN
resources/soccer_ball.aseprite
Normal file
BIN
resources/soccer_ball.aseprite
Normal file
Binary file not shown.
BIN
resources/soccer_ball.png
Normal file
BIN
resources/soccer_ball.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.2 KiB |
@@ -1,5 +1,4 @@
|
||||
#include "ball.h"
|
||||
#include "defines.h"
|
||||
|
||||
// Constructor
|
||||
Ball::Ball(int x, int y, int w, int h, int vx, int vy, Texture *texture)
|
||||
@@ -13,8 +12,8 @@ Ball::Ball(int x, int y, int w, int h, int vx, int vy, Texture *texture)
|
||||
sprite = new Sprite(texture);
|
||||
sprite->setPos({x, y});
|
||||
sprite->setSize(w, h);
|
||||
sprite->setClip({0, 0, 24, 24});
|
||||
color = {255, 255, 255};
|
||||
sprite->setClip({0, 0, static_cast<float>(w), static_cast<float>(h)});
|
||||
color = {(rand() % 192) + 32, (rand() % 192) + 32, (rand() % 192) + 32};
|
||||
}
|
||||
|
||||
// Destructor
|
||||
@@ -46,9 +45,9 @@ void Ball::update()
|
||||
collision = true;
|
||||
}
|
||||
|
||||
if (x + w > SCREEN_WIDTH)
|
||||
if (x + w > DEMO_WIDTH)
|
||||
{
|
||||
x = SCREEN_WIDTH - w;
|
||||
x = DEMO_WIDTH - w;
|
||||
vx = -luckyX;
|
||||
collision = true;
|
||||
}
|
||||
@@ -60,16 +59,16 @@ void Ball::update()
|
||||
collision = true;
|
||||
}
|
||||
|
||||
if (y + h > SCREEN_HEIGHT)
|
||||
if (y + h > DEMO_HEIGHT)
|
||||
{
|
||||
y = SCREEN_HEIGHT - h;
|
||||
y = DEMO_HEIGHT - h;
|
||||
vy = -luckyY;
|
||||
collision = true;
|
||||
}
|
||||
|
||||
if (collision)
|
||||
{
|
||||
color = {rand() % 255, rand() % 255, rand() % 255};
|
||||
sprite->setAnimationSpeed((rand() % 15) + 5);
|
||||
}
|
||||
|
||||
// Actualiza la posición del sprite
|
||||
|
||||
@@ -13,7 +13,7 @@ private:
|
||||
int w; // Ancho
|
||||
int h; // Alto
|
||||
int vx, vy; // Velocidad
|
||||
color_t color; // Color de la pelota
|
||||
Color color; // Color de la pelota
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#define SCREEN_WIDTH 320
|
||||
#define SCREEN_HEIGHT 240
|
||||
#define NUM_BALLS 100
|
||||
constexpr Uint64 DEMO_SPEED = 1000/60;
|
||||
|
||||
struct color_t
|
||||
constexpr int DEMO_WIDTH = 480;
|
||||
constexpr int DEMO_HEIGHT = 360;
|
||||
constexpr int WINDOW_ZOOM = 2;
|
||||
constexpr int NUM_BALLS = 100;
|
||||
constexpr int BALL_SIZE = 36;
|
||||
constexpr int NUM_FRAMES = 4;
|
||||
|
||||
constexpr int BG_R = 96;
|
||||
constexpr int BG_G = 96;
|
||||
constexpr int BG_B = 96;
|
||||
|
||||
constexpr char TEXTURE_FILE[] = "resources/soccer_ball.png";
|
||||
|
||||
struct Color
|
||||
{
|
||||
int r,g,b;
|
||||
int r, g, b;
|
||||
};
|
||||
250
source/main.cpp
250
source/main.cpp
@@ -1,152 +1,188 @@
|
||||
#include <SDL2/SDL.h>
|
||||
#include "texture.h"
|
||||
#include "ball.h"
|
||||
#include "defines.h"
|
||||
#include <iostream>
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
SDL_Window *window = NULL;
|
||||
SDL_Renderer *renderer = NULL;
|
||||
SDL_Event *event;
|
||||
// Ventana principal y renderizador
|
||||
SDL_Window *window = nullptr;
|
||||
SDL_Renderer *renderer = nullptr;
|
||||
|
||||
// Textura y bolas
|
||||
Texture *texture = nullptr;
|
||||
Ball *ball[NUM_BALLS];
|
||||
|
||||
bool shouldExit = false;
|
||||
Uint32 ticks = 0;
|
||||
// Control de la aplicación
|
||||
bool should_exit = false;
|
||||
Uint64 ticks = 0;
|
||||
|
||||
// Inicializa SDL, la ventana, el renderizador y los elementos del juego
|
||||
bool init()
|
||||
{
|
||||
// Initialization flag
|
||||
bool success = true;
|
||||
// Indicador de inicialización exitosa
|
||||
bool success = true;
|
||||
|
||||
// Initialize SDL
|
||||
if (SDL_Init(SDL_INIT_VIDEO) < 0)
|
||||
{
|
||||
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
|
||||
success = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create window
|
||||
window = SDL_CreateWindow("demo_pelotas1", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH * 2, SCREEN_HEIGHT * 2, SDL_WINDOW_SHOWN);
|
||||
if (window == NULL)
|
||||
{
|
||||
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
|
||||
success = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create renderer for window
|
||||
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
|
||||
if (renderer == NULL)
|
||||
{
|
||||
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
|
||||
success = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Initialize renderer color
|
||||
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
||||
// Inicializar SDL
|
||||
if (!SDL_Init(SDL_INIT_VIDEO))
|
||||
{
|
||||
std::cout << "¡SDL no pudo inicializarse! Error de SDL: " << SDL_GetError() << std::endl;
|
||||
success = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Crear ventana
|
||||
window = SDL_CreateWindow("demo_pelotas1", DEMO_WIDTH * WINDOW_ZOOM, DEMO_HEIGHT * WINDOW_ZOOM, SDL_WINDOW_OPENGL);
|
||||
if (window == nullptr)
|
||||
{
|
||||
std::cout << "¡No se pudo crear la ventana! Error de SDL: " << SDL_GetError() << std::endl;
|
||||
success = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Crear renderizador para la ventana
|
||||
renderer = SDL_CreateRenderer(window, nullptr);
|
||||
if (renderer == nullptr)
|
||||
{
|
||||
std::cout << "¡No se pudo crear el renderizador! Error de SDL: " << SDL_GetError() << std::endl;
|
||||
success = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Establecer el color inicial del renderizador
|
||||
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
|
||||
|
||||
SDL_RenderSetLogicalSize(renderer, SCREEN_WIDTH, SCREEN_HEIGHT);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Configurar el renderizador para usar una presentación lógica
|
||||
SDL_SetRenderLogicalPresentation(renderer, DEMO_WIDTH, DEMO_HEIGHT, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
event = new SDL_Event();
|
||||
// Crear textura y bolas
|
||||
texture = new Texture(renderer, TEXTURE_FILE);
|
||||
for (int i = 0; i < NUM_BALLS; ++i)
|
||||
{
|
||||
const int VX = rand() % 2 == 0 ? 1 : -1;
|
||||
const int VY = rand() % 2 == 0 ? 1 : -1;
|
||||
const int X = rand() % DEMO_WIDTH;
|
||||
const int Y = rand() % DEMO_HEIGHT;
|
||||
constexpr int SIZE = BALL_SIZE;
|
||||
ball[i] = new Ball(X, Y, SIZE, SIZE, VX, VY, texture);
|
||||
}
|
||||
|
||||
texture = new Texture(renderer, "resources/pelota.png");
|
||||
for (int i = 0; i < NUM_BALLS; ++i)
|
||||
{
|
||||
ball[i] = new Ball(rand() % SCREEN_WIDTH, rand() % SCREEN_HEIGHT, 24, 24, 1, 1, texture);
|
||||
}
|
||||
// Configuración inicial de tiempos
|
||||
ticks = SDL_GetTicks();
|
||||
srand(time(nullptr));
|
||||
|
||||
ticks = SDL_GetTicks();
|
||||
|
||||
return success;
|
||||
return success;
|
||||
}
|
||||
|
||||
// Limpia y libera todos los recursos
|
||||
void close()
|
||||
{
|
||||
// Destroy window
|
||||
SDL_DestroyRenderer(renderer);
|
||||
SDL_DestroyWindow(window);
|
||||
window = NULL;
|
||||
renderer = NULL;
|
||||
// Destruir el renderizador y la ventana
|
||||
SDL_DestroyRenderer(renderer);
|
||||
SDL_DestroyWindow(window);
|
||||
|
||||
if (event)
|
||||
{
|
||||
delete event;
|
||||
}
|
||||
// Eliminar la textura
|
||||
if (texture)
|
||||
{
|
||||
delete texture;
|
||||
}
|
||||
|
||||
if (texture)
|
||||
{
|
||||
delete texture;
|
||||
}
|
||||
// Eliminar todas las bolas
|
||||
for (int i = 0; i < NUM_BALLS; ++i)
|
||||
{
|
||||
if (ball[i])
|
||||
{
|
||||
delete ball[i];
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < NUM_BALLS; ++i)
|
||||
{
|
||||
if (ball[i])
|
||||
{
|
||||
delete ball[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Quit SDL subsystems
|
||||
SDL_Quit();
|
||||
// Finalizar SDL
|
||||
SDL_Quit();
|
||||
}
|
||||
|
||||
// Gestiona los eventos del usuario
|
||||
void checkEvents()
|
||||
{
|
||||
// Comprueba los eventos que hay en la cola
|
||||
while (SDL_PollEvent(event) != 0)
|
||||
{
|
||||
// Evento de salida de la aplicación
|
||||
if (event->type == SDL_QUIT)
|
||||
{
|
||||
shouldExit = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
SDL_Event event;
|
||||
|
||||
// Procesar todos los eventos en la cola
|
||||
while (SDL_PollEvent(&event) != 0)
|
||||
{
|
||||
// Detectar si el usuario quiere cerrar la aplicación
|
||||
if (event.type == SDL_EVENT_QUIT)
|
||||
{
|
||||
should_exit = true;
|
||||
break;
|
||||
}
|
||||
|
||||
// Manejar eventos de teclado
|
||||
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 0)
|
||||
{
|
||||
switch (event.key.key)
|
||||
{
|
||||
case SDLK_ESCAPE: // Salir de la aplicación
|
||||
should_exit = true;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Actualiza el estado de las bolas
|
||||
void update()
|
||||
{
|
||||
if (SDL_GetTicks() - ticks > 15)
|
||||
{
|
||||
ticks = SDL_GetTicks();
|
||||
if (SDL_GetTicks() - ticks > DEMO_SPEED)
|
||||
{
|
||||
ticks = SDL_GetTicks();
|
||||
|
||||
for (int i = 0; i < NUM_BALLS; ++i)
|
||||
{
|
||||
ball[i]->update();
|
||||
}
|
||||
}
|
||||
// Actualizar la posición de cada bola
|
||||
for (int i = 0; i < NUM_BALLS; ++i)
|
||||
{
|
||||
ball[i]->update();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dibuja el estado actual en la pantalla
|
||||
void render()
|
||||
{
|
||||
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
||||
SDL_RenderClear(renderer);
|
||||
// Limpiar la pantalla con el color de fondo
|
||||
SDL_SetRenderDrawColor(renderer, BG_R, BG_G, BG_B, 255);
|
||||
SDL_RenderClear(renderer);
|
||||
|
||||
for (int i = 0; i < NUM_BALLS; ++i)
|
||||
{
|
||||
ball[i]->render();
|
||||
}
|
||||
// Dibujar todas las bolas
|
||||
for (int i = 0; i < NUM_BALLS; ++i)
|
||||
{
|
||||
ball[i]->render();
|
||||
}
|
||||
|
||||
SDL_RenderPresent(renderer);
|
||||
// Presentar el renderizador
|
||||
SDL_RenderPresent(renderer);
|
||||
}
|
||||
|
||||
// Función principal
|
||||
int main(int argc, char *args[])
|
||||
{
|
||||
init();
|
||||
if (!init())
|
||||
{
|
||||
return -1; // Salir si la inicialización falla
|
||||
}
|
||||
|
||||
while (!shouldExit)
|
||||
{
|
||||
update();
|
||||
checkEvents();
|
||||
render();
|
||||
}
|
||||
// Bucle principal del juego
|
||||
while (!should_exit)
|
||||
{
|
||||
update();
|
||||
checkEvents();
|
||||
render();
|
||||
}
|
||||
|
||||
close();
|
||||
// Limpiar y cerrar la aplicación
|
||||
close();
|
||||
|
||||
return 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -3,65 +3,67 @@
|
||||
// Constructor
|
||||
Sprite::Sprite(Texture *texture)
|
||||
{
|
||||
this->texture = texture;
|
||||
pos = {0, 0, 0, 0};
|
||||
clip = {0, 0, 0, 0};
|
||||
frame = 0;
|
||||
numFrames = 3;
|
||||
animationSpeed = 20;
|
||||
animationCounter = 0;
|
||||
}
|
||||
|
||||
// Destructor
|
||||
Sprite::~Sprite()
|
||||
{
|
||||
texture_ = texture;
|
||||
pos_ = {0, 0, 0, 0};
|
||||
clip_ = {0, 0, 0, 0};
|
||||
frame_ = 0;
|
||||
num_frames_ = NUM_FRAMES;
|
||||
animation_speed_ = 20;
|
||||
animation_counter_ = 0;
|
||||
}
|
||||
|
||||
// Establece la posición del sprite
|
||||
void Sprite::setPos(SDL_Point pos)
|
||||
{
|
||||
this->pos.x = pos.x;
|
||||
this->pos.y = pos.y;
|
||||
pos_.x = pos.x;
|
||||
pos_.y = pos.y;
|
||||
}
|
||||
|
||||
// Pinta el sprite
|
||||
void Sprite::render()
|
||||
{
|
||||
texture->render(&clip, &pos);
|
||||
texture_->render(&clip_, &pos_);
|
||||
}
|
||||
|
||||
// Actualiza la lógica de la clase
|
||||
void Sprite::update()
|
||||
{
|
||||
animationCounter++;
|
||||
if (animationCounter % animationSpeed == 0)
|
||||
animation_counter_++;
|
||||
if (animation_counter_ % animation_speed_ == 0)
|
||||
{
|
||||
animate();
|
||||
}
|
||||
}
|
||||
|
||||
// Establece el rectangulo de la textura que se va a pintar
|
||||
void Sprite::setClip(SDL_Rect clip)
|
||||
void Sprite::setClip(SDL_FRect clip)
|
||||
{
|
||||
this->clip = clip;
|
||||
clip_ = clip;
|
||||
}
|
||||
|
||||
// Establece el tamaño del sprite
|
||||
void Sprite::setSize(int w, int h)
|
||||
{
|
||||
this->pos.w = w;
|
||||
this->pos.h = h;
|
||||
pos_.w = w;
|
||||
pos_.h = h;
|
||||
}
|
||||
|
||||
// Anima el sprite
|
||||
void Sprite::animate()
|
||||
{
|
||||
frame = (frame + 1) % numFrames;
|
||||
clip.x = frame * pos.w;
|
||||
frame_ = (frame_ + 1) % num_frames_;
|
||||
clip_.x = frame_ * pos_.w;
|
||||
}
|
||||
|
||||
// Modulación de color
|
||||
void Sprite::setColor(int r, int g, int b)
|
||||
{
|
||||
texture->setColor(r, g, b);
|
||||
texture_->setColor(r, g, b);
|
||||
}
|
||||
|
||||
// Cambia la velocidad de la animación
|
||||
void Sprite::setAnimationSpeed(int value)
|
||||
{
|
||||
animation_speed_ = value;
|
||||
animation_counter_ = 0;
|
||||
}
|
||||
@@ -1,28 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
#include "texture.h"
|
||||
#include "defines.h"
|
||||
|
||||
class Sprite
|
||||
{
|
||||
private:
|
||||
Texture *texture; // Textura con los gráficos del sprite
|
||||
SDL_Rect pos; // Posición y tamaño del sprite
|
||||
SDL_Rect clip; // Parte de la textura que se va a dibujar
|
||||
int frame; // Frame a dibujar de la textura definido en clip
|
||||
int numFrames; // Numero total de frames
|
||||
int animationSpeed; // Velocidad de animación
|
||||
int animationCounter; // Contador para la animación
|
||||
Texture *texture_; // Textura con los gráficos del sprite
|
||||
SDL_FRect pos_; // Posición y tamaño del sprite
|
||||
SDL_FRect clip_; // Parte de la textura que se va a dibujar
|
||||
int frame_; // Frame a dibujar de la textura definido en clip
|
||||
int num_frames_; // Numero total de frames
|
||||
int animation_speed_; // Velocidad de animación
|
||||
int animation_counter_; // Contador para la animación
|
||||
|
||||
// Anima el sprite
|
||||
void animate();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
Sprite(Texture *texture);
|
||||
explicit Sprite(Texture *texture);
|
||||
|
||||
// Destructor
|
||||
~Sprite();
|
||||
~Sprite() = default;
|
||||
|
||||
// Establece la posición del sprite
|
||||
void setPos(SDL_Point pos);
|
||||
@@ -34,11 +34,14 @@ public:
|
||||
void update();
|
||||
|
||||
// Establece el rectangulo de la textura que se va a pintar
|
||||
void setClip(SDL_Rect clip);
|
||||
void setClip(SDL_FRect clip);
|
||||
|
||||
// Establece el tamaño del sprite
|
||||
void setSize(int w, int h);
|
||||
|
||||
// Modulación de color
|
||||
void setColor(int r, int g, int b);
|
||||
|
||||
// Cambia la velocidad de la animación
|
||||
void setAnimationSpeed(int value);
|
||||
};
|
||||
@@ -5,20 +5,12 @@
|
||||
#include "texture.h"
|
||||
|
||||
Texture::Texture(SDL_Renderer *renderer)
|
||||
{
|
||||
this->renderer = renderer;
|
||||
texture = NULL;
|
||||
width = 0;
|
||||
height = 0;
|
||||
}
|
||||
: renderer_(renderer), texture_(nullptr), width_(0), height_(0) {}
|
||||
|
||||
Texture::Texture(SDL_Renderer *renderer, std::string filepath)
|
||||
Texture::Texture(SDL_Renderer *renderer, std::string file_path)
|
||||
: renderer_(renderer), texture_(nullptr), width_(0), height_(0)
|
||||
{
|
||||
this->renderer = renderer;
|
||||
texture = NULL;
|
||||
width = 0;
|
||||
height = 0;
|
||||
loadFromFile(filepath);
|
||||
loadFromFile(file_path);
|
||||
}
|
||||
|
||||
Texture::~Texture()
|
||||
@@ -26,12 +18,12 @@ Texture::~Texture()
|
||||
free();
|
||||
}
|
||||
|
||||
bool Texture::loadFromFile(std::string path)
|
||||
bool Texture::loadFromFile(std::string file_path)
|
||||
{
|
||||
const std::string filename = path.substr(path.find_last_of("\\/") + 1);
|
||||
const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
int req_format = STBI_rgb_alpha;
|
||||
int width, height, orig_format;
|
||||
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
|
||||
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
||||
if (data == nullptr)
|
||||
{
|
||||
SDL_Log("Loading image failed: %s", stbi_failure_reason());
|
||||
@@ -39,20 +31,18 @@ bool Texture::loadFromFile(std::string path)
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Image loaded: " << filename.c_str() << std::endl;
|
||||
std::cout << "Image loaded: " << filename.c_str() << std::endl;
|
||||
}
|
||||
|
||||
int depth, pitch;
|
||||
Uint32 pixel_format;
|
||||
int pitch;
|
||||
SDL_PixelFormat pixel_format;
|
||||
if (req_format == STBI_rgb)
|
||||
{
|
||||
depth = 24;
|
||||
pitch = 3 * width; // 3 bytes por pixel * pixels por linea
|
||||
pixel_format = SDL_PIXELFORMAT_RGB24;
|
||||
}
|
||||
else
|
||||
{ // STBI_rgb_alpha (RGBA)
|
||||
depth = 32;
|
||||
pitch = 4 * width;
|
||||
pixel_format = SDL_PIXELFORMAT_RGBA32;
|
||||
}
|
||||
@@ -61,69 +51,69 @@ bool Texture::loadFromFile(std::string path)
|
||||
free();
|
||||
|
||||
// La textura final
|
||||
SDL_Texture *newTexture = nullptr;
|
||||
SDL_Texture *new_texture = nullptr;
|
||||
|
||||
// Carga la imagen desde una ruta específica
|
||||
SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void *)data, width, height, depth, pitch, pixel_format);
|
||||
if (loadedSurface == nullptr)
|
||||
SDL_Surface *loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, (void *)data, pitch);
|
||||
if (loaded_surface == nullptr)
|
||||
{
|
||||
std::cout << "Unable to load image " << path.c_str() << std::endl;
|
||||
std::cout << "Unable to load image " << file_path << std::endl;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Crea la textura desde los pixels de la surface
|
||||
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
|
||||
if (newTexture == nullptr)
|
||||
new_texture = SDL_CreateTextureFromSurface(renderer_, loaded_surface);
|
||||
if (new_texture == nullptr)
|
||||
{
|
||||
std::cout << "Unable to create texture from " << path.c_str() << "! SDL Error: " << SDL_GetError() << std::endl;
|
||||
std::cout << "Unable to create texture from " << file_path << "! SDL Error: " << SDL_GetError() << std::endl;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Obtiene las dimensiones de la imagen
|
||||
this->width = loadedSurface->w;
|
||||
this->height = loadedSurface->h;
|
||||
width_ = loaded_surface->w;
|
||||
height_ = loaded_surface->h;
|
||||
}
|
||||
|
||||
// Elimina la textura cargada
|
||||
SDL_FreeSurface(loadedSurface);
|
||||
SDL_DestroySurface(loaded_surface);
|
||||
}
|
||||
|
||||
// Return success
|
||||
stbi_image_free(data);
|
||||
texture = newTexture;
|
||||
return texture != nullptr;
|
||||
texture_ = new_texture;
|
||||
return texture_ != nullptr;
|
||||
}
|
||||
|
||||
void Texture::free()
|
||||
{
|
||||
// Free texture if it exists
|
||||
if (texture != NULL)
|
||||
if (texture_ != NULL)
|
||||
{
|
||||
SDL_DestroyTexture(texture);
|
||||
texture = NULL;
|
||||
width = 0;
|
||||
height = 0;
|
||||
SDL_DestroyTexture(texture_);
|
||||
texture_ = NULL;
|
||||
width_ = 0;
|
||||
height_ = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void Texture::render(SDL_Rect *src, SDL_Rect *dst)
|
||||
void Texture::render(SDL_FRect *src, SDL_FRect *dst)
|
||||
{
|
||||
// Render to screen
|
||||
SDL_RenderCopy(renderer, texture, src, dst);
|
||||
SDL_RenderTexture(renderer_, texture_, src, dst);
|
||||
}
|
||||
|
||||
int Texture::getWidth()
|
||||
{
|
||||
return width;
|
||||
return width_;
|
||||
}
|
||||
|
||||
int Texture::getHeight()
|
||||
{
|
||||
return height;
|
||||
return height_;
|
||||
}
|
||||
|
||||
// Modulación de color
|
||||
void Texture::setColor(int r, int g, int b)
|
||||
{
|
||||
SDL_SetTextureColorMod(texture, r, g, b);
|
||||
SDL_SetTextureColorMod(texture_, r, g, b);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
#include <SDL3/SDL.h>
|
||||
#include <iostream>
|
||||
|
||||
// Texture wrapper class
|
||||
class Texture
|
||||
{
|
||||
private:
|
||||
SDL_Renderer *renderer;
|
||||
SDL_Texture *texture;
|
||||
SDL_Renderer *renderer_;
|
||||
SDL_Texture *texture_;
|
||||
|
||||
// Image dimensions
|
||||
int width;
|
||||
int height;
|
||||
int width_;
|
||||
int height_;
|
||||
|
||||
public:
|
||||
// Initializes variables
|
||||
Texture(SDL_Renderer *renderer);
|
||||
Texture(SDL_Renderer *renderer, std::string filepath);
|
||||
Texture(SDL_Renderer *renderer, std::string file_path);
|
||||
|
||||
// Deallocates memory
|
||||
~Texture();
|
||||
@@ -29,7 +29,7 @@ public:
|
||||
void free();
|
||||
|
||||
// Renders texture at given point
|
||||
void render(SDL_Rect *src = nullptr, SDL_Rect *dst = nullptr);
|
||||
void render(SDL_FRect *src = nullptr, SDL_FRect *dst = nullptr);
|
||||
|
||||
// Gets image dimensions
|
||||
int getWidth();
|
||||
|
||||
Reference in New Issue
Block a user