Actualizadas las clases sprite, movingsprite y animatedsprite

This commit is contained in:
2022-08-29 20:02:46 +02:00
parent 47c57a9f44
commit 9c2140b274
29 changed files with 726 additions and 802 deletions

View File

@@ -8,10 +8,11 @@ roomRight=02.room
[tilemap] [tilemap]
01.tmx 01.tmx
[tilemap-end] [/tilemap]
[enemy] [enemy]
tileset=paco.png tileset=paco.png
animation=paco.ani
width=16 width=16
height=16 height=16
x=1 x=1
@@ -23,10 +24,11 @@ y1=0
x2=1 x2=1
y2=6 y2=6
color=red color=red
[enemy-end] [/enemy]
[enemy] [enemy]
tileset=paco.png tileset=paco.png
animation=paco.ani
width=16 width=16
height=16 height=16
x=5 x=5
@@ -38,18 +40,18 @@ y1=9
x2=22 x2=22
y2=9 y2=9
color=yellow color=yellow
[enemy-end] [/enemy]
[item] [item]
tileset=items.png tileset=items.png
tile=0 tile=0
x=1 x=1
y=7 y=7
[item-end] [/item]
[item] [item]
tileset=items.png tileset=items.png
tile=0 tile=0
x=17 x=17
y=8 y=8
[item-end] [/item]

View File

@@ -8,10 +8,11 @@ roomRight=03.room
[tilemap] [tilemap]
02.tmx 02.tmx
[tilemap-end] [/tilemap]
[enemy] [enemy]
tileset=paco.png tileset=paco.png
animation=paco.ani
width=16 width=16
height=16 height=16
x=14 x=14
@@ -23,11 +24,11 @@ y1=0
x2=14 x2=14
y2=12 y2=12
color=purple color=purple
[enemy-end] [/enemy]
[item] [item]
tileset=items.png tileset=items.png
tile=1 tile=1
x=19 x=19
y=6 y=6
[item-end] [/item]

View File

@@ -8,10 +8,11 @@ roomRight=0
[tilemap] [tilemap]
03.tmx 03.tmx
[tilemap-end] [/tilemap]
[enemy] [enemy]
tileset=chip.png tileset=chip.png
animation=chip.ani
width=8 width=8
height=16 height=16
x=4 x=4
@@ -23,10 +24,11 @@ y1=2
x2=4 x2=4
y2=13 y2=13
color=green color=green
[enemy-end] [/enemy]
[enemy] [enemy]
tileset=chip.png tileset=chip.png
animation=chip.ani
width=8 width=8
height=16 height=16
x=10 x=10
@@ -38,10 +40,11 @@ y1=2
x2=10 x2=10
y2=13 y2=13
color=light_blue color=light_blue
[enemy-end] [/enemy]
[enemy] [enemy]
tileset=chip.png tileset=chip.png
animation=chip.ani
width=8 width=8
height=16 height=16
x=16 x=16
@@ -53,11 +56,11 @@ y1=2
x2=16 x2=16
y2=13 y2=13
color=purple color=purple
[enemy-end] [/enemy]
[item] [item]
tileset=items.png tileset=items.png
tile=5 tile=5
x=12 x=12
y=2 y=2
[item-end] [/item]

View File

@@ -8,10 +8,11 @@ roomRight=05.room
[tilemap] [tilemap]
04.tmx 04.tmx
[tilemap-end] [/tilemap]
[enemy] [enemy]
tileset=chip.png tileset=chip.png
animation=chip.ani
width=8 width=8
height=16 height=16
x=1 x=1
@@ -23,10 +24,11 @@ y1=3
x2=14 x2=14
y2=3 y2=3
color=purple color=purple
[enemy-end] [/enemy]
[enemy] [enemy]
tileset=chip.png tileset=chip.png
animation=chip.ani
width=8 width=8
height=16 height=16
x=30 x=30
@@ -38,10 +40,11 @@ y1=7
x2=30 x2=30
y2=7 y2=7
color=light_white color=light_white
[enemy-end] [/enemy]
[enemy] [enemy]
tileset=wave.png tileset=wave.png
animation=wave.ani
width=8 width=8
height=8 height=8
x=15 x=15
@@ -53,21 +56,21 @@ y1=12
x2=30 x2=30
y2=12 y2=12
color=light_purple color=light_purple
[enemy-end] [/enemy]
[item] [item]
tileset=items.png tileset=items.png
tile=6 tile=6
x=2 x=2
y=2 y=2
[item-end] [/item]
[item] [item]
tileset=items.png tileset=items.png
tile=6 tile=6
x=29 x=29
y=5 y=5
[item-end] [/item]
[item] [item]
@@ -75,4 +78,4 @@ tileset=items.png
tile=6 tile=6
x=21 x=21
y=12 y=12
[item-end] [/item]

View File

@@ -8,4 +8,4 @@ roomRight=0
[tilemap] [tilemap]
05.tmx 05.tmx
[tilemap-end] [/tilemap]

10
media/enemies/chip.ani Normal file
View File

@@ -0,0 +1,10 @@
frames_per_row=4
frame_width=8
frame_height=16
[animation]
name=default
speed=8
loop=0
frames=0,1,2,3
[/animation]

10
media/enemies/paco.ani Normal file
View File

@@ -0,0 +1,10 @@
frames_per_row=4
frame_width=16
frame_height=16
[animation]
name=default
speed=8
loop=0
frames=0,1,2,3
[/animation]

10
media/enemies/wave.ani Normal file
View File

@@ -0,0 +1,10 @@
frames_per_row=4
frame_width=8
frame_height=8
[animation]
name=default
speed=8
loop=0
frames=0,1,2,3
[/animation]

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

BIN
media/font/debug.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 689 B

View File

@@ -1,137 +1,137 @@
# box width # box width
8 5
# box height # box height
8 5
# 32 espacio ( ) # 32 espacio ( )
2 5
# 33 ! # 33 !
2 5
# 34 " # 34 "
5 5
# 35 # # 35 #
6 5
# 36 $ # 36 $
6 5
# 37 % # 37 %
6 5
# 38 & # 38 &
6 5
# 39 ' # 39 '
2 5
# 40 ( # 40 (
3 5
# 41 ) # 41 )
3 5
# 42 * # 42 *
4 5
# 43 + # 43 +
3 5
# 44 , # 44 ,
2 5
# 45 - # 45 -
3 5
# 46 . # 46 .
2 5
# 47 / # 47 /
4 5
# 48 0 # 48 0
6 5
# 49 1 # 49 1
6 5
# 50 2 # 50 2
6 5
# 51 3 # 51 3
6 5
# 52 4 # 52 4
6 5
# 53 5 # 53 5
6 5
# 54 6 # 54 6
6 5
# 55 7 # 55 7
6 5
# 56 8 # 56 8
6 5
# 57 9 # 57 9
6 5
# 58 : # 58 :
2 5
# 59 ; # 59 ;
2 5
# 60 < # 60 <
4 5
# 61 = # 61 =
3 5
# 62 > # 62 >
4 5
# 63 ? # 63 ?
6 5
# 64 @ # 64 @
8 5
# 65 A # 65 A
6 5
# 66 B # 66 B
6 5
# 67 C # 67 C
6 5
# 68 D # 68 D
6 5
# 69 E # 69 E
6 5
# 70 F # 70 F
6 5
# 71 G # 71 G
6 5
# 72 H # 72 H
6 5
# 73 I # 73 I
6 5
# 74 J # 74 J
6 5
# 75 K # 75 K
6 5
# 76 L # 76 L
6 5
# 77 M # 77 M
6 5
# 78 N # 78 N
6 5
# 79 O # 79 O
6 5
# 80 P # 80 P
6 5
# 81 Q # 81 Q
6 5
# 82 R # 82 R
6 5
# 83 S # 83 S
6 5
# 84 T # 84 T
6 5
# 85 U # 85 U
6 5
# 86 V # 86 V
5 5
# 87 W # 87 W
6 5
# 88 X # 88 X
6 5
# 89 Y # 89 Y
6 5
# 90 Z # 90 Z
6 5
# 91 [ # 91 [
3 5
# 92 \ # 92 \
5 5
# 93 ] # 93 ]
3 5
# 94 ^ # 94 ^
4 5
# 95 _ # 95 _
6 5
# 96 ` # 96 `
2 5
# 97 a # 97 a
5 5
# 98 b # 98 b
@@ -149,7 +149,7 @@
# 104 h # 104 h
5 5
# 105 i # 105 i
4 5
# 106 j # 106 j
5 5
# 107 k # 107 k
@@ -157,7 +157,7 @@
# 108 l # 108 l
5 5
# 109 m # 109 m
6 5
# 110 n # 110 n
5 5
# 111 o # 111 o
@@ -171,24 +171,24 @@
# 115 s # 115 s
5 5
# 116 t # 116 t
4 5
# 117 u # 117 u
5 5
# 118 v # 118 v
5 5
# 119 w # 119 w
6 5
# 120 x # 120 x
4 5
# 121 y # 121 y
4 5
# 122 z # 122 z
5 5
# 123 { # 123 {
3 5
# 124 | # 124 |
2 5
# 125 } # 125 }
3 5
# 126 ~ # 126 ~
3 5

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

View File

@@ -1,194 +0,0 @@
# box width
10
# box height
10
# 32 espacio ( )
5
# 33 !
4
# 34 "
5
# 35 #
7
# 36 $
7
# 37 %
8
# 38 &
8
# 39 '
3
# 40 (
5
# 41 )
5
# 42 *
7
# 43 +
7
# 44 ,
4
# 45 -
6
# 46 .
4
# 47 /
5
# 48 0
7
# 49 1
5
# 50 2
7
# 51 3
7
# 52 4
7
# 53 5
7
# 54 6
7
# 55 7
7
# 56 8
7
# 57 9
7
# 58 :
4
# 59 ;
4
# 60 <
6
# 61 =
6
# 62 >
6
# 63 ?
7
# 64 @
8
# 65 A
7
# 66 B
7
# 67 C
7
# 68 D
7
# 69 E
7
# 70 F
7
# 71 G
7
# 72 H
7
# 73 I
4
# 74 J
6
# 75 K
8
# 76 L
6
# 77 M
9
# 78 N
8
# 79 O
8
# 80 P
7
# 81 Q
8
# 82 R
7
# 83 S
6
# 84 T
8
# 85 U
7
# 86 V
8
# 87 W
9
# 88 X
8
# 89 Y
8
# 90 Z
7
# 91 [
4
# 92 \
5
# 93 ]
4
# 94 ^
5
# 95 _
8
# 96 `
4
# 97 a
7
# 98 b
7
# 99 c
6
# 100 d
7
# 101 e
7
# 102 f
5
# 103 g
7
# 104 h
7
# 105 i
4
# 106 j
5
# 107 k
7
# 108 l
4
# 109 m
10
# 110 n
7
# 111 o
7
# 112 p
7
# 113 q
7
# 114 r
6
# 115 s
6
# 116 t
5
# 117 u
7
# 118 v
7
# 119 w
9
# 120 x
7
# 121 y
7
# 122 z
7
# 123 { -> ñ
7
# 124 | -> ç
7
# 125 }
0
# 126 ~
0

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

View File

@@ -1,194 +0,0 @@
# box width
10
# box height
10
# 32 espacio ( )
5
# 33 !
4
# 34 "
5
# 35 #
7
# 36 $
7
# 37 %
8
# 38 &
8
# 39 '
3
# 40 (
5
# 41 )
5
# 42 *
7
# 43 +
7
# 44 ,
4
# 45 -
6
# 46 .
4
# 47 /
5
# 48 0
7
# 49 1
5
# 50 2
7
# 51 3
7
# 52 4
7
# 53 5
7
# 54 6
7
# 55 7
7
# 56 8
7
# 57 9
7
# 58 :
4
# 59 ;
4
# 60 <
6
# 61 =
6
# 62 >
6
# 63 ?
7
# 64 @
8
# 65 A
7
# 66 B
7
# 67 C
7
# 68 D
7
# 69 E
7
# 70 F
7
# 71 G
7
# 72 H
7
# 73 I
4
# 74 J
6
# 75 K
8
# 76 L
6
# 77 M
9
# 78 N
8
# 79 O
8
# 80 P
7
# 81 Q
8
# 82 R
7
# 83 S
6
# 84 T
8
# 85 U
7
# 86 V
8
# 87 W
9
# 88 X
8
# 89 Y
8
# 90 Z
7
# 91 [
4
# 92 \
5
# 93 ]
4
# 94 ^
5
# 95 _
8
# 96 `
4
# 97 a
7
# 98 b
7
# 99 c
6
# 100 d
7
# 101 e
7
# 102 f
5
# 103 g
7
# 104 h
7
# 105 i
4
# 106 j
5
# 107 k
7
# 108 l
4
# 109 m
10
# 110 n
7
# 111 o
7
# 112 p
7
# 113 q
7
# 114 r
6
# 115 s
6
# 116 t
5
# 117 u
7
# 118 v
7
# 119 w
9
# 120 x
7
# 121 y
7
# 122 z
7
# 123 { -> ñ
7
# 124 | -> ç
7
# 125 }
0
# 126 ~
0

17
media/player/player01.ani Normal file
View File

@@ -0,0 +1,17 @@
frames_per_row=4
frame_width=8
frame_height=16
[animation]
name=stand
speed=8
loop=0
frames=0
[/animation]
[animation]
name=walk
speed=8
loop=0
frames=0,1,2,3
[/animation]

View File

@@ -2,123 +2,266 @@
#include "animatedsprite.h" #include "animatedsprite.h"
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(LTexture *texture, SDL_Renderer *renderer) AnimatedSprite::AnimatedSprite(LTexture *texture, SDL_Renderer *renderer, std::string file)
{ {
// Copia los punteros // Copia los punteros
setTexture(texture); setTexture(texture);
setRenderer(renderer); setRenderer(renderer);
init(); // Carga las animaciones
load(file);
// Inicializa variables
currentAnimation = 0;
} }
// Destructor // Destructor
AnimatedSprite::~AnimatedSprite() AnimatedSprite::~AnimatedSprite()
{ {
for (auto &a : animation)
{
a.frames.clear();
}
animation.clear();
} }
// Iniciador // Obtiene el indice de la animación a partir del nombre
void AnimatedSprite::init() int AnimatedSprite::getIndex(std::string name)
{ {
for (int i = 0; i < 20; i++) int index = -1;
for (int i = 0; i < animation.size(); i++)
{ {
mAnimation[i].numFrames = 0; if (animation[i].name == name)
mAnimation[i].speed = 0;
mAnimation[i].loop = true;
mAnimation[i].completed = false;
for (int j = 0; i < 20; i++)
{ {
mAnimation[i].frames[j].x = 0; index = i;
mAnimation[i].frames[j].y = 0;
mAnimation[i].frames[j].w = 0;
mAnimation[i].frames[j].h = 0;
} }
} }
mCurrentFrame = 0;
mAnimationCounter = 0; if (index == -1)
{
printf("** Warning: could not find \"%s\" animation\n", name.c_str());
index = 0;
}
return index;
} }
// Calcula el frame correspondiente a la animación // Calcula el frame correspondiente a la animación
void AnimatedSprite::animate(int index) void AnimatedSprite::animate()
{ {
if (mEnabled) if (enabled)
{ {
// Calculamos el frame actual a partir del contador // Calcula el frame actual a partir del contador
mCurrentFrame = mAnimationCounter / mAnimation[index].speed; animation[currentAnimation].currentFrame = animation[currentAnimation].counter / animation[currentAnimation].speed;
// Si alcanzamos el final de la animación, reiniciamos el contador de la animación // Si alcanza el final de la animación, reinicia el contador de la animación
// en función de la variable loop // en función de la variable loop y coloca el nuevo frame
if (mCurrentFrame >= mAnimation[index].numFrames) if (animation[currentAnimation].currentFrame >= animation[currentAnimation].frames.size())
{ {
if (mAnimation[index].loop) if (animation[currentAnimation].loop == -1)
mAnimationCounter = 0; { // Si no hay loop, deja el último frame
animation[currentAnimation].currentFrame = animation[currentAnimation].frames.size();
animation[currentAnimation].completed = true;
}
else else
mCurrentFrame = mAnimation[index].numFrames; { // Si hay loop, vuelve al frame indicado
animation[currentAnimation].counter = 0;
animation[currentAnimation].currentFrame = animation[currentAnimation].loop;
}
} }
// En caso contrario // En caso contrario
else else
{ {
// Escogemos el frame correspondiente de la animación // Escoge el frame correspondiente de la animación
setSpriteClip(mAnimation[index].frames[mCurrentFrame]); setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]);
// Incrementamos el contador de la animacion // Incrementa el contador de la animacion
mAnimationCounter++; animation[currentAnimation].counter++;
} }
} }
} }
// Establece el frame actual de la animación // Establece el frame actual de la animación
void AnimatedSprite::setCurrentFrame(Uint8 num) void AnimatedSprite::setCurrentFrame(std::string name, int num)
{ {
mCurrentFrame = num; animation[getIndex(name)].currentFrame = num;
} }
// Establece el valor del contador // Establece el valor del contador
void AnimatedSprite::setAnimationCounter(Uint16 num) void AnimatedSprite::setAnimationCounter(std::string name, int num)
{ {
mAnimationCounter = num; animation[getIndex(name)].counter = num;
}
// Establece el rectangulo para un frame de una animación
void AnimatedSprite::setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h)
{
mAnimation[index_animation].frames[index_frame].x = x;
mAnimation[index_animation].frames[index_frame].y = y;
mAnimation[index_animation].frames[index_frame].w = w;
mAnimation[index_animation].frames[index_frame].h = h;
} }
// Establece la velocidad de una animación // Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(Uint8 index, Uint8 speed) void AnimatedSprite::setAnimationSpeed(std::string name, int speed)
{ {
mAnimation[index].speed = speed; animation[getIndex(name)].counter = speed;
}
// Establece el numero de frames de una animación
void AnimatedSprite::setAnimationNumFrames(Uint8 index, Uint8 num)
{
mAnimation[index].numFrames = num;
} }
// Establece si la animación se reproduce en bucle // Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(Uint8 index, bool loop) void AnimatedSprite::setAnimationLoop(std::string name, int loop)
{ {
mAnimation[index].loop = loop; animation[getIndex(name)].loop = loop;
} }
// Establece el valor de la variable // Establece el valor de la variable
void AnimatedSprite::setCompleted(Uint8 index, bool value) void AnimatedSprite::setAnimationCompleted(std::string name, bool value)
{ {
mAnimation[index].completed = value; animation[getIndex(name)].completed = value;
} }
// Comprueba si ha terminado la animación // Comprueba si ha terminado la animación
bool AnimatedSprite::isCompleted(Uint8 index) bool AnimatedSprite::animationIsCompleted()
{ {
return mAnimation[index].completed; return animation[currentAnimation].completed;
} }
// Devuelve el rectangulo de una animación y frame concreto // Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(Uint8 index_animation, Uint8 index_frame) SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index)
{ {
return mAnimation[index_animation].frames[index_frame]; return animation[getIndex(name)].frames[index];
}
// Carga la animación desde un fichero
bool AnimatedSprite::load(std::string filePath)
{
int frames_per_row = 0;
int frame_width = 0;
int frame_height = 0;
// Indicador de éxito en la carga
bool success = true;
const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1);
std::ifstream file(filePath);
std::string line;
// El fichero se puede abrir
if (file.good())
{
// Procesa el fichero linea a linea
printf("Reading file %s\n", filename.c_str());
while (std::getline(file, line))
{
// Si la linea contiene el texto [enemy] se realiza el proceso de carga de un enemigo
if (line == "[animation]")
{
t_animation buffer;
buffer.counter = 0;
buffer.currentFrame = 0;
buffer.completed = false;
do
{
std::getline(file, line);
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != line.npos)
{
if (line.substr(0, pos) == "name")
{
buffer.name = line.substr(pos + 1, line.length());
}
else if (line.substr(0, pos) == "speed")
{
buffer.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop")
{
buffer.loop = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frames")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp;
SDL_Rect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ','))
{
int num_tile = std::stoi(tmp);
rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height;
buffer.frames.push_back(rect);
}
}
else
{
printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str());
success = false;
}
}
} while (line != "[/animation]");
// Añade el enemigo al vector de enemigos
animation.push_back(buffer);
}
// En caso contrario se parsea el fichero para buscar las variables y los valores
else
{
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != line.npos)
{
if (line.substr(0, pos) == "frames_per_row")
{
frames_per_row = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frame_width")
{
frame_width = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frame_height")
{
frame_height = std::stoi(line.substr(pos + 1, line.length()));
}
else
{
printf("Warning: file %s, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str());
success = false;
}
}
}
}
// Cierra el fichero
printf("Closing file %s\n\n", filename.c_str());
file.close();
}
// El fichero no se puede abrir
else
{
printf("Warning: Unable to open %s file\n", filename.c_str());
success = false;
}
// Pone un valor por defecto
setPos({0, 0, frame_width, frame_height});
return success;
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(std::string name)
{
const int newAnimation = getIndex(name);
if (currentAnimation != newAnimation)
{
currentAnimation = newAnimation;
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
}
}
// Actualiza las variables del objeto
void AnimatedSprite::update()
{
animate();
MovingSprite::update();
} }

View File

@@ -1,69 +1,74 @@
#pragma once #pragma once
#include "ifdefs.h"
#include <SDL2/SDL.h>
#include "movingsprite.h" #include "movingsprite.h"
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#ifndef ANIMATEDSPRITE_H #ifndef ANIMATEDSPRITE_H
#define ANIMATEDSPRITE_H #define ANIMATEDSPRITE_H
#define MAX_FRAMES 30
#define MAX_ANIMATIONS 20
// Clase AnimatedSprite // Clase AnimatedSprite
class AnimatedSprite : public MovingSprite class AnimatedSprite : public MovingSprite
{ {
private: private:
struct sAnimation struct t_animation
{ {
SDL_Rect frames[MAX_FRAMES]; // Cada uno de los frames que componen la animación std::string name; // Nombre de la animacion
Uint8 numFrames; // Numero de frames que componen la animación std::vector<SDL_Rect> frames; // Cada uno de los frames que componen la animación
Uint8 speed; // Velocidad de la animación int speed; // Velocidad de la animación
bool loop; // Indica si la animación se reproduce en bucle int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed; // Indica si ha finalizado la animación bool completed; // Indica si ha finalizado la animación
int currentFrame; // Frame actual
int counter; // Contador para las animaciones
}; };
sAnimation mAnimation[MAX_ANIMATIONS]; // Vector con las diferentes animaciones std::vector<t_animation> animation; // Vector con las diferentes animaciones
int currentAnimation; // Animacion activa
Uint8 mCurrentFrame; // Frame actual
Uint16 mAnimationCounter; // Contador para las animaciones
public: public:
// Constructor // Constructor
AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr); AnimatedSprite(LTexture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "");
// Destructor // Destructor
~AnimatedSprite(); ~AnimatedSprite();
// Iniciador // Calcula el frame correspondiente a la animación actual
void init(); void animate();
// Calcula el frame correspondiente a la animación
void animate(int index);
// Establece el frame actual de la animación // Establece el frame actual de la animación
void setCurrentFrame(Uint8 num); void setCurrentFrame(std::string name, int num);
// Establece el valor del contador // Establece el valor del contador
void setAnimationCounter(Uint16 num); void setAnimationCounter(std::string name, int num);
// 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);
// Establece la velocidad de una animación // Establece la velocidad de una animación
void setAnimationSpeed(Uint8 index, Uint8 speed); void setAnimationSpeed(std::string name, int speed);
// Establece el numero de frames de una animación // Establece el frame al que vuelve la animación al finalizar
void setAnimationNumFrames(Uint8 index, Uint8 num); void setAnimationLoop(std::string name, int loop);
// Establece si la animación se reproduce en bucle
void setAnimationLoop(Uint8 index, bool loop);
// Establece el valor de la variable // Establece el valor de la variable
void setCompleted(Uint8 index, bool value); void setAnimationCompleted(std::string name, bool value);
// Comprueba si ha terminado la animación // Comprueba si ha terminado la animación
bool isCompleted(Uint8 index); bool animationIsCompleted();
// Devuelve el rectangulo de una animación y frame concreto // Devuelve el rectangulo de una animación y frame concreto
SDL_Rect getAnimationClip(Uint8 index_animation, Uint8 index_frame); SDL_Rect getAnimationClip(std::string name, Uint8 index);
// Obtiene el indice de la animación a partir del nombre
int getIndex(std::string name);
// Carga la animación desde un fichero
bool load(std::string filePath);
// Establece la animacion actual
void setCurrentAnimation(std::string name = "default");
// Actualiza las variables del objeto
void update();
}; };
#endif #endif

View File

@@ -173,17 +173,10 @@ bool Director::initSDL()
// Crea el indice de ficheros // Crea el indice de ficheros
void Director::setFileList() void Director::setFileList()
{ {
mAsset->add("/media/font/8bithud.png", font);
mAsset->add("/media/font/8bithud.txt", font);
mAsset->add("/media/font/nokia.png", font);
mAsset->add("/media/font/nokia.txt", font);
mAsset->add("/media/font/nokia2.png", font);
mAsset->add("/media/font/nokia2.txt", font);
mAsset->add("/media/font/smb2.png", font); mAsset->add("/media/font/smb2.png", font);
mAsset->add("/media/font/smb2.txt", font); mAsset->add("/media/font/smb2.txt", font);
mAsset->add("/media/lang/es_ES.txt", lang); mAsset->add("/media/font/debug.png", font);
mAsset->add("/media/lang/en_UK.txt", lang); mAsset->add("/media/font/debug.txt", font);
mAsset->add("/media/lang/ba_BA.txt", lang);
mAsset->add("/data/gamecontrollerdb.txt", data); mAsset->add("/data/gamecontrollerdb.txt", data);
mAsset->add("/data/config.bin", data, false); mAsset->add("/data/config.bin", data, false);
mAsset->add("/data/room/01.room", room); mAsset->add("/data/room/01.room", room);
@@ -198,9 +191,13 @@ void Director::setFileList()
mAsset->add("/data/room/05.tmx", room); mAsset->add("/data/room/05.tmx", room);
mAsset->add("/media/tilesets/standard.png", bitmap); mAsset->add("/media/tilesets/standard.png", bitmap);
mAsset->add("/media/enemies/paco.png", bitmap); mAsset->add("/media/enemies/paco.png", bitmap);
mAsset->add("/media/enemies/paco.ani", data);
mAsset->add("/media/enemies/chip.png", bitmap); mAsset->add("/media/enemies/chip.png", bitmap);
mAsset->add("/media/enemies/chip.ani", data);
mAsset->add("/media/enemies/wave.png", bitmap); mAsset->add("/media/enemies/wave.png", bitmap);
mAsset->add("/media/enemies/wave.ani", data);
mAsset->add("/media/player/player01.png", bitmap); mAsset->add("/media/player/player01.png", bitmap);
mAsset->add("/media/player/player01.ani", data);
mAsset->add("/media/items/items.png", bitmap); mAsset->add("/media/items/items.png", bitmap);
} }

View File

@@ -11,10 +11,8 @@ Enemy::Enemy(enemy_t enemy)
// Crea objetos // Crea objetos
texture = new LTexture(); texture = new LTexture();
sprite = new AnimatedSprite(texture, renderer);
// Carga la textura
loadTextureFromFile(texture, asset->get(enemy.tileset), renderer); loadTextureFromFile(texture, asset->get(enemy.tileset), renderer);
sprite = new AnimatedSprite(texture, renderer, asset->get(enemy.animation));
// Obten el resto de valores // Obten el resto de valores
x1 = enemy.x1; x1 = enemy.x1;
@@ -26,20 +24,8 @@ Enemy::Enemy(enemy_t enemy)
sprite->setPosY(enemy.y); sprite->setPosY(enemy.y);
sprite->setVelX(enemy.vx); sprite->setVelX(enemy.vx);
sprite->setVelY(enemy.vy); sprite->setVelY(enemy.vy);
// Inicializa el sprite con el resto de parametros comunes
sprite->setWidth(enemy.w); sprite->setWidth(enemy.w);
sprite->setHeight(enemy.h); sprite->setHeight(enemy.h);
sprite->setCurrentFrame(0);
sprite->setAnimationCounter(0);
sprite->setAnimationNumFrames(0, 4);
sprite->setAnimationSpeed(0, 5);
sprite->setAnimationLoop(0, true);
sprite->setAnimationFrames(0, 0, enemy.w * 0, 0, enemy.w, enemy.h);
sprite->setAnimationFrames(0, 1, enemy.w * 1, 0, enemy.w, enemy.h);
sprite->setAnimationFrames(0, 2, enemy.w * 2, 0, enemy.w, enemy.h);
sprite->setAnimationFrames(0, 3, enemy.w * 3, 0, enemy.w, enemy.h);
sprite->setSpriteClip(sprite->getAnimationClip(0, 0));
collider = getRect(); collider = getRect();
} }
@@ -67,7 +53,7 @@ void Enemy::render()
void Enemy::update() void Enemy::update()
{ {
sprite->update(); sprite->update();
sprite->animate(0); sprite->animate();
checkPath(); checkPath();
collider = getRect(); collider = getRect();
} }

View File

@@ -29,6 +29,7 @@ struct enemy_t
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
std::string tileset; // Fichero con los graficos del enemigo std::string tileset; // Fichero con los graficos del enemigo
std::string animation; // Fichero con las animaciones del enemigo
int w; // Anchura del enemigo int w; // Anchura del enemigo
int h; // Altura del enemigo int h; // Altura del enemigo
float x; // Posición inicial en el eje X float x; // Posición inicial en el eje X

View File

@@ -17,7 +17,7 @@ Game::Game(SDL_Window *window, SDL_Renderer *renderer, Asset *asset, Input *inpu
screen = new Screen(window, renderer); screen = new Screen(window, renderer);
itemTracker = new ItemTracker(); itemTracker = new ItemTracker();
room = new Room(asset->get(currentRoom), renderer, asset, itemTracker); room = new Room(asset->get(currentRoom), renderer, asset, itemTracker);
player = new Player(spawnPoint, asset->get("player01.png"), renderer, asset, input, room); player = new Player(spawnPoint, asset->get("player01.png"), asset->get("player01.ani"), renderer, asset, input, room);
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
text = new Text(asset->get("smb2.png"), asset->get("smb2.txt"), renderer); text = new Text(asset->get("smb2.png"), asset->get("smb2.txt"), renderer);
@@ -332,5 +332,5 @@ void Game::killPlayer()
// Crea la nueva habitación y el nuevo jugador // Crea la nueva habitación y el nuevo jugador
room = new Room(asset->get(currentRoom), renderer, asset, itemTracker); room = new Room(asset->get(currentRoom), renderer, asset, itemTracker);
player = new Player(spawnPoint, asset->get("player01.png"), renderer, asset, input, room); player = new Player(spawnPoint, asset->get("player01.png"), asset->get("player01.ani"), renderer, asset, input, room);
} }

View File

@@ -5,48 +5,50 @@
MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, LTexture *texture, SDL_Renderer *renderer) MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, LTexture *texture, SDL_Renderer *renderer)
{ {
// Copia los punteros // Copia los punteros
setTexture(texture); this->texture = texture;
setRenderer(renderer); this->renderer = renderer;
// Establece el alto y el ancho del sprite // Establece el alto y el ancho del sprite
setWidth(w); this->w = w;
setHeight(h); this->h = h;
// Establece la posición X,Y del sprite // Establece la posición X,Y del sprite
setPosX(x); this->x = x;
setPosY(y); this->y = y;
xPrev = x;
yPrev = y;
// Establece la velocidad X,Y del sprite // Establece la velocidad X,Y del sprite
setVelX(velx); vx = velx;
setVelY(vely); vy = vely;
// Establece la aceleración X,Y del sprite // Establece la aceleración X,Y del sprite
setAccelX(accelx); ax = accelx;
setAccelY(accely); ay = accely;
// Establece el zoom W,H del sprite // Establece el zoom W,H del sprite
setZoomW(1); zoomW = 1;
setZoomH(1); zoomH = 1;
// Establece el angulo con el que se dibujará // Establece el angulo con el que se dibujará
setAngle(0.0); angle = (double)0;
// Establece los valores de rotacion // Establece los valores de rotacion
setRotate(false); rotateEnabled = false;
setRotateSpeed(0); rotateSpeed = 0;
setRotateAmount(0.0); rotateAmount = (double)0;
// Contador interno // Contador interno
mCounter = 0; counter = 0;
// Establece el rectangulo de donde coger la imagen // Establece el rectangulo de donde coger la imagen
setSpriteClip(0, 0, w, h); spriteClip = {0, 0, w, h};
// Establece el centro de rotación // Establece el centro de rotación
mCenter = {0,0}; center = {0, 0};
// Establece el tipo de volteado // Establece el tipo de volteado
mFlip = SDL_FLIP_NONE; currentFlip = SDL_FLIP_NONE;
}; };
// Destructor // Destructor
@@ -57,189 +59,199 @@ MovingSprite::~MovingSprite()
// Reinicia todas las variables // Reinicia todas las variables
void MovingSprite::clear() void MovingSprite::clear()
{ {
mPosX = 0.0f; // Posición en el eje X x = 0.0f; // Posición en el eje X
mPosY = 0.0f; // Posición en el eje Y y = 0.0f; // Posición en el eje Y
mVelX = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse vx = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
mVelY = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse vy = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
mAccelX = 0.0f; // Aceleración en el eje X. Variación de la velocidad ax = 0.0f; // Aceleración en el eje X. Variación de la velocidad
mAccelY = 0.0f; // Aceleración en el eje Y. Variación de la velocidad ay = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
mZoomW = 1.0f; // Zoom aplicado a la anchura zoomW = 1.0f; // Zoom aplicado a la anchura
mZoomH = 1.0f; // Zoom aplicado a la altura zoomH = 1.0f; // Zoom aplicado a la altura
mAngle = 0.0; // Angulo para dibujarlo angle = 0.0; // Angulo para dibujarlo
mRotate = false; // Indica si ha de rotar rotateEnabled = false; // Indica si ha de rotar
mCenter = {0, 0}; // Centro de rotación center = {0, 0}; // Centro de rotación
mRotateSpeed = 0; // Velocidad de giro rotateSpeed = 0; // Velocidad de giro
mRotateAmount = 0.0; // Cantidad de grados a girar en cada iteración rotateAmount = 0.0; // Cantidad de grados a girar en cada iteración
mCounter = 0; // Contador interno counter = 0; // Contador interno
mFlip = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite currentFlip = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
} }
// Mueve el sprite // Mueve el sprite
void MovingSprite::move() void MovingSprite::move()
{ {
if (mEnabled) if (enabled)
{ {
mPosX += mVelX; xPrev = x;
mPosY += mVelY; yPrev = y;
mVelX += mAccelX; x += vx;
mVelY += mAccelY; y += vy;
vx += ax;
vy += ay;
} }
} }
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
void MovingSprite::render() void MovingSprite::render()
{ {
if (mEnabled) if (enabled)
mTexture->render(mRenderer, (int)mPosX, (int)mPosY, &mSpriteClip, mZoomW, mZoomH, mAngle, &mCenter, mFlip); texture->render(renderer, (int)x, (int)y, &spriteClip, zoomW, zoomH, angle, &center, currentFlip);
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float MovingSprite::getPosX() float MovingSprite::getPosX()
{ {
return mPosX; return x;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float MovingSprite::getPosY() float MovingSprite::getPosY()
{ {
return mPosY; return y;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float MovingSprite::getVelX() float MovingSprite::getVelX()
{ {
return mVelX; return vx;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float MovingSprite::getVelY() float MovingSprite::getVelY()
{ {
return mVelY; return vy;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float MovingSprite::getAccelX() float MovingSprite::getAccelX()
{ {
return mAccelX; return ax;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float MovingSprite::getAccelY() float MovingSprite::getAccelY()
{ {
return mAccelY; return ay;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float MovingSprite::getZoomW() float MovingSprite::getZoomW()
{ {
return mZoomW; return zoomW;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
float MovingSprite::getZoomH() float MovingSprite::getZoomH()
{ {
return mZoomH; return zoomH;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
double MovingSprite::getAngle() double MovingSprite::getAngle()
{ {
return mAngle; return angle;
}
// Establece la posición del objeto
void MovingSprite::setPos(SDL_Rect rect)
{
x = (float)rect.x;
y = (float)rect.y;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setPosX(float x) void MovingSprite::setPosX(float value)
{ {
mPosX = x; x = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setPosY(float y) void MovingSprite::setPosY(float value)
{ {
mPosY = y; y = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setVelX(float x) void MovingSprite::setVelX(float value)
{ {
mVelX = x; vx = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setVelY(float y) void MovingSprite::setVelY(float value)
{ {
mVelY = y; vy = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setAccelX(float x) void MovingSprite::setAccelX(float value)
{ {
mAccelX = x; ax = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setAccelY(float y) void MovingSprite::setAccelY(float value)
{ {
mAccelY = y; ay = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setZoomW(float w) void MovingSprite::setZoomW(float value)
{ {
mZoomW = w; zoomW = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setZoomH(float h) void MovingSprite::setZoomH(float value)
{ {
mZoomH = h; zoomH = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setAngle(double a) void MovingSprite::setAngle(double value)
{ {
mAngle = a; angle = value;
} }
// Incrementa el valor de la variable // Incrementa el valor de la variable
void MovingSprite::incAngle(double inc) void MovingSprite::incAngle(double value)
{ {
mAngle += inc; angle += value;
} }
// Decrementa el valor de la variable // Decrementa el valor de la variable
void MovingSprite::decAngle(double dec) void MovingSprite::decAngle(double value)
{ {
mAngle -= dec; angle -= value;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool MovingSprite::getRotate() bool MovingSprite::getRotate()
{ {
return mRotate; return rotateEnabled;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 MovingSprite::getRotateSpeed() Uint16 MovingSprite::getRotateSpeed()
{ {
return mRotateSpeed; return rotateSpeed;
} }
// Establece la rotacion // Establece la rotacion
void MovingSprite::rotate() void MovingSprite::rotate()
{ {
if (mEnabled) if (enabled)
if (mRotate) if (rotateEnabled)
{ {
if (mCounter % mRotateSpeed == 0) if (counter % rotateSpeed == 0)
{ {
incAngle(mRotateAmount); incAngle(rotateAmount);
} }
} }
} }
@@ -247,26 +259,26 @@ void MovingSprite::rotate()
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setRotate(bool value) void MovingSprite::setRotate(bool value)
{ {
mRotate = value; rotateEnabled = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setRotateSpeed(Uint16 value) void MovingSprite::setRotateSpeed(int value)
{ {
mRotateSpeed = value; rotateSpeed = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setRotateAmount(double value) void MovingSprite::setRotateAmount(double value)
{ {
mRotateAmount = value; rotateAmount = value;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::disableRotate() void MovingSprite::disableRotate()
{ {
mRotate = false; rotateEnabled = false;
mAngle = 0; angle = (double)0;
} }
// Actualiza las variables internas del objeto // Actualiza las variables internas del objeto
@@ -275,31 +287,79 @@ void MovingSprite::update()
move(); move();
rotate(); rotate();
if (mEnabled) if (enabled)
++mCounter %= 60000; {
++counter %= 60000;
}
} }
// Cambia el sentido de la rotación // Cambia el sentido de la rotación
void MovingSprite::switchRotate() void MovingSprite::switchRotate()
{ {
mRotateAmount *= -1; rotateAmount *= -1;
} }
// Establece el valor de la variable // Establece el valor de la variable
void MovingSprite::setFlip(SDL_RendererFlip flip) void MovingSprite::setFlip(SDL_RendererFlip flip)
{ {
mFlip = flip; currentFlip = flip;
}
// Gira el sprite horizontalmente
void MovingSprite::flip()
{
currentFlip = (currentFlip == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
SDL_RendererFlip MovingSprite::getFlip() SDL_RendererFlip MovingSprite::getFlip()
{ {
return mFlip; return currentFlip;
} }
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
SDL_Rect MovingSprite::getRect() SDL_Rect MovingSprite::getRect()
{ {
SDL_Rect rect = {(int)getPosX(), (int)getPosY(), getWidth(), getHeight()}; const SDL_Rect rect = {(int)x, (int)y, w, h};
return rect; return rect;
}
// Establece los valores de posición y tamaño del sprite
void MovingSprite::setRect(SDL_Rect rect)
{
x = (float)rect.x;
y = (float)rect.y;
w = rect.w;
h = rect.h;
}
// Deshace el último movimiento
void MovingSprite::undoMove()
{
x = xPrev;
y = yPrev;
}
// Deshace el último movimiento en el eje X
void MovingSprite::undoMoveX()
{
x = xPrev;
}
// Deshace el último movimiento en el eje Y
void MovingSprite::undoMoveY()
{
y = yPrev;
}
// Pone a cero las velocidades de desplacamiento
void MovingSprite::clearVel()
{
vx = vy = 0.0f;
}
// Devuelve el incremento en el eje X en pixels
int MovingSprite::getIncX()
{
return (int)x - (int)xPrev;
} }

View File

@@ -1,5 +1,6 @@
#pragma once #pragma once
#include "ifdefs.h"
#include <SDL2/SDL.h>
#include "sprite.h" #include "sprite.h"
#ifndef MOVINGSPRITE_H #ifndef MOVINGSPRITE_H
@@ -9,25 +10,28 @@
class MovingSprite : public Sprite class MovingSprite : public Sprite
{ {
protected: protected:
float mPosX; // Posición en el eje X float x; // Posición en el eje X
float mPosY; // Posición en el eje Y float y; // Posición en el eje Y
float mVelX; // Velocidad en el eje X. Cantidad de pixeles a desplazarse float xPrev; // Posición anterior en el eje X
float mVelY; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse float yPrev; // Posición anterior en el eje Y
float mAccelX; // Aceleración en el eje X. Variación de la velocidad float vx; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float mAccelY; // Aceleración en el eje Y. Variación de la velocidad float vy; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float mZoomW; // Zoom aplicado a la anchura float ax; // Aceleración en el eje X. Variación de la velocidad
float mZoomH; // Zoom aplicado a la altura float ay; // Aceleración en el eje Y. Variación de la velocidad
double mAngle; // Angulo para dibujarlo float zoomW; // Zoom aplicado a la anchura
bool mRotate; // Indica si ha de rotar float zoomH; // Zoom aplicado a la altura
Uint16 mRotateSpeed; // Velocidad de giro
double mRotateAmount; // Cantidad de grados a girar en cada iteración double angle; // Angulo para dibujarlo
Uint16 mCounter; // Contador interno bool rotateEnabled; // Indica si ha de rotar
SDL_Point mCenter; // Centro de rotación int rotateSpeed; // Velocidad de giro
SDL_RendererFlip mFlip; // Indica como se voltea el sprite 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
public: public:
// Constructor // Constructor
@@ -84,44 +88,47 @@ public:
// Obtiene el valor de la variable // Obtiene el valor de la variable
Uint16 getRotateSpeed(); Uint16 getRotateSpeed();
// Establece el valor de la variable // Establece la posición del objeto
void setPosX(float x); void setPos(SDL_Rect rect);
// Establece el valor de la variable // Establece el valor de la variable
void setPosY(float y); void setPosX(float value);
// Establece el valor de la variable // Establece el valor de la variable
void setVelX(float x); void setPosY(float value);
// Establece el valor de la variable // Establece el valor de la variable
void setVelY(float y); void setVelX(float value);
// Establece el valor de la variable // Establece el valor de la variable
void setAccelX(float x); void setVelY(float value);
// Establece el valor de la variable // Establece el valor de la variable
void setAccelY(float y); void setAccelX(float value);
// Establece el valor de la variable // Establece el valor de la variable
void setZoomW(float w); void setAccelY(float value);
// Establece el valor de la variable // Establece el valor de la variable
void setZoomH(float h); void setZoomW(float value);
// Establece el valor de la variable // Establece el valor de la variable
void setAngle(double a); void setZoomH(float value);
// Establece el valor de la variable
void setAngle(double vaue);
// Incrementa el valor de la variable // Incrementa el valor de la variable
void incAngle(double inc); void incAngle(double value);
// Decrementa el valor de la variable // Decrementa el valor de la variable
void decAngle(double dec); void decAngle(double value);
// Establece el valor de la variable // Establece el valor de la variable
void setRotate(bool value); void setRotate(bool value);
// Establece el valor de la variable // Establece el valor de la variable
void setRotateSpeed(Uint16 value); void setRotateSpeed(int value);
// Establece el valor de la variable // Establece el valor de la variable
void setRotateAmount(double value); void setRotateAmount(double value);
@@ -135,11 +142,32 @@ public:
// Establece el valor de la variable // Establece el valor de la variable
void setFlip(SDL_RendererFlip flip); void setFlip(SDL_RendererFlip flip);
// Gira el sprite horizontalmente
void flip();
// Obtiene el valor de la variable // Obtiene el valor de la variable
SDL_RendererFlip getFlip(); SDL_RendererFlip getFlip();
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
SDL_Rect getRect(); SDL_Rect getRect();
// Establece los valores de posición y tamaño del sprite
void setRect(SDL_Rect rect);
// Deshace el último movimiento
void undoMove();
// Deshace el último movimiento en el eje X
void undoMoveX();
// Deshace el último movimiento en el eje Y
void undoMoveY();
// Pone a cero las velocidades de desplacamiento
void clearVel();
// Devuelve el incremento en el eje X en pixels
int getIncX();
}; };
#endif #endif

View File

@@ -5,19 +5,19 @@
// CAUTION!!!!! si no se gasta al final, quitar la referencia a la habitación // CAUTION!!!!! si no se gasta al final, quitar la referencia a la habitación
// Constructor // Constructor
Player::Player(player_t ini, std::string _tileset, SDL_Renderer *_renderer, Asset *_asset, Input *_input, Room *_room) Player::Player(player_t ini, std::string tileset, std::string animation, SDL_Renderer *renderer, Asset *asset, Input *input, Room *room)
{ {
// Obten punteros a objetos // Obten punteros a objetos
asset = _asset; this->asset = asset;
renderer = _renderer; this->renderer = renderer;
input = _input; this->input = input;
// Crea objetos // Crea objetos
texture = new LTexture(); texture = new LTexture();
sprite = new AnimatedSprite(texture, renderer); sprite = new AnimatedSprite(texture, renderer, animation);
// Carga la textura // Carga la textura
loadTextureFromFile(texture, asset->get(_tileset), renderer); loadTextureFromFile(texture, asset->get(tileset), renderer);
// Inicializa variables // Inicializa variables
color = stringToColor("white"); color = stringToColor("white");
@@ -31,19 +31,8 @@ Player::Player(player_t ini, std::string _tileset, SDL_Renderer *_renderer, Asse
sprite->setPosY(ini.y); sprite->setPosY(ini.y);
sprite->setVelX(ini.vx); sprite->setVelX(ini.vx);
sprite->setVelY(ini.vy); sprite->setVelY(ini.vy);
sprite->setWidth(8); sprite->setWidth(8);
sprite->setHeight(16); sprite->setHeight(16);
sprite->setCurrentFrame(0);
sprite->setAnimationCounter(0);
sprite->setAnimationNumFrames(0, 4);
sprite->setAnimationSpeed(0, 5);
sprite->setAnimationLoop(0, true);
sprite->setAnimationFrames(0, 0, 8 * 0, 0, 8, 16);
sprite->setAnimationFrames(0, 1, 8 * 1, 0, 8, 16);
sprite->setAnimationFrames(0, 2, 8 * 2, 0, 8, 16);
sprite->setAnimationFrames(0, 3, 8 * 3, 0, 8, 16);
sprite->setSpriteClip(sprite->getAnimationClip(0, 0));
sprite->setFlip(ini.flip); sprite->setFlip(ini.flip);
@@ -270,7 +259,11 @@ void Player::move()
sprite->update(); sprite->update();
if (sprite->getVelX() != 0) if (sprite->getVelX() != 0)
{ {
sprite->animate(0); sprite->setCurrentAnimation("walk");
}
else
{
sprite->setCurrentAnimation("stand");
} }
} }

View File

@@ -27,7 +27,7 @@ struct player_t
float vy; float vy;
int jump_ini; int jump_ini;
int status; int status;
SDL_RendererFlip flip; SDL_RendererFlip flip;
}; };
// Clase Player // Clase Player
@@ -73,7 +73,7 @@ public:
int status; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo int status; // Estado en el que se encuentra el jugador. Util apara saber si está saltando o cayendo
// Constructor // Constructor
Player(player_t ini, std::string _tileset, SDL_Renderer *_renderer, Asset *_asset, Input *_input, Room *_room); Player(player_t ini, std::string tileset, std::string animation, SDL_Renderer *renderer, Asset *asset, Input *input, Room *room);
// Destructor // Destructor
~Player(); ~Player();

View File

@@ -85,7 +85,7 @@ bool Room::load(std::string _file_path)
printf("Warning: file %s\n, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str()); printf("Warning: file %s\n, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str());
success = false; success = false;
} }
} while (line != "[enemy-end]"); } while (line != "[/enemy]");
// Añade el enemigo al vector de enemigos // Añade el enemigo al vector de enemigos
enemies.push_back(new Enemy(enemy)); enemies.push_back(new Enemy(enemy));
@@ -140,7 +140,7 @@ bool Room::load(std::string _file_path)
} }
} }
} }
} while (line != "[tilemap-end]"); } while (line != "[/tilemap]");
} }
// Si la linea contiene el texto [item] se realiza el proceso de carga de un item // Si la linea contiene el texto [item] se realiza el proceso de carga de un item
@@ -162,7 +162,7 @@ bool Room::load(std::string _file_path)
printf("Warning: file %s\n, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str()); printf("Warning: file %s\n, unknown parameter \"%s\"\n", filename.c_str(), line.substr(0, pos).c_str());
success = false; success = false;
} }
} while (line != "[item-end]"); } while (line != "[/item]");
// Añade el item al vector de items // Añade el item al vector de items
const SDL_Point itemPos = {item.x, item.y}; const SDL_Point itemPos = {item.x, item.y};
@@ -265,53 +265,71 @@ bool Room::setEnemy(enemy_t *enemy, std::string var, std::string value)
{ {
enemy->tileset = value; enemy->tileset = value;
} }
else if (var == "animation")
{
enemy->animation = value;
}
else if (var == "width") else if (var == "width")
{ {
enemy->w = std::stof(value); enemy->w = std::stof(value);
} }
else if (var == "height") else if (var == "height")
{ {
enemy->h = std::stof(value); enemy->h = std::stof(value);
} }
else if (var == "x") else if (var == "x")
{ {
enemy->x = std::stof(value) * BLOCK; enemy->x = std::stof(value) * BLOCK;
} }
else if (var == "y") else if (var == "y")
{ {
enemy->y = std::stof(value) * BLOCK; enemy->y = std::stof(value) * BLOCK;
} }
else if (var == "vx") else if (var == "vx")
{ {
enemy->vx = std::stof(value); enemy->vx = std::stof(value);
} }
else if (var == "vy") else if (var == "vy")
{ {
enemy->vy = std::stof(value); enemy->vy = std::stof(value);
} }
else if (var == "x1") else if (var == "x1")
{ {
enemy->x1 = std::stoi(value) * BLOCK; enemy->x1 = std::stoi(value) * BLOCK;
} }
else if (var == "x2") else if (var == "x2")
{ {
enemy->x2 = std::stoi(value) * BLOCK; enemy->x2 = std::stoi(value) * BLOCK;
} }
else if (var == "y1") else if (var == "y1")
{ {
enemy->y1 = std::stoi(value) * BLOCK; enemy->y1 = std::stoi(value) * BLOCK;
} }
else if (var == "y2") else if (var == "y2")
{ {
enemy->y2 = std::stoi(value) * BLOCK; enemy->y2 = std::stoi(value) * BLOCK;
} }
else if (var == "color") else if (var == "color")
{ {
enemy->color = stringToColor(value); enemy->color = stringToColor(value);
} }
else if (var == "[enemy-end]")
else if (var == "[/enemy]")
{ {
} }
else else
{ {
success = false; success = false;
@@ -330,21 +348,26 @@ bool Room::setItem(item_t *item, std::string var, std::string value)
{ {
item->tileset = value; item->tileset = value;
} }
else if (var == "x") else if (var == "x")
{ {
item->x = std::stof(value) * BLOCK; item->x = std::stof(value) * BLOCK;
} }
else if (var == "y") else if (var == "y")
{ {
item->y = std::stof(value) * BLOCK; item->y = std::stof(value) * BLOCK;
} }
else if (var == "tile") else if (var == "tile")
{ {
item->tile = std::stof(value); item->tile = std::stof(value);
} }
else if (var == "[item-end]")
else if (var == "[/item]")
{ {
} }
else else
{ {
success = false; success = false;

View File

@@ -3,168 +3,181 @@
// Constructor // Constructor
Sprite::Sprite(int x, int y, int w, int h, LTexture *texture, SDL_Renderer *renderer) Sprite::Sprite(int x, int y, int w, int h, LTexture *texture, SDL_Renderer *renderer)
{ {
// Establece el alto y el ancho del sprite
setWidth(w);
setHeight(h);
// Establece la posición X,Y del sprite // Establece la posición X,Y del sprite
setPosX(x); this->x = x;
setPosY(y); this->y = y;
// Establece el alto y el ancho del sprite
this->w = w;
this->h = h;
// Establece el puntero al renderizador de la ventana // Establece el puntero al renderizador de la ventana
setRenderer(renderer); this->renderer = renderer;
// Establece la textura donde están los gráficos para el sprite // Establece la textura donde están los gráficos para el sprite
setTexture(texture); this->texture = texture;
// Establece el rectangulo de donde coger la imagen // Establece el rectangulo de donde coger la imagen
setSpriteClip(x, y, w, h); spriteClip = {x, y, w, h};
// Inicializa variables // Inicializa variables
setEnabled(true); enabled = true;
} }
Sprite::Sprite(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer) Sprite::Sprite(SDL_Rect rect, LTexture *texture, SDL_Renderer *renderer)
{ {
// Establece el alto y el ancho del sprite
setWidth(rect.w);
setHeight(rect.h);
// Establece la posición X,Y del sprite // Establece la posición X,Y del sprite
setPosX(rect.x); x = rect.x;
setPosY(rect.y); y = rect.y;
// Establece el alto y el ancho del sprite
w = rect.w;
h = rect.h;
// Establece el puntero al renderizador de la ventana // Establece el puntero al renderizador de la ventana
setRenderer(renderer); this->renderer = renderer;
// Establece la textura donde están los gráficos para el sprite // Establece la textura donde están los gráficos para el sprite
setTexture(texture); this->texture = texture;
// Establece el rectangulo de donde coger la imagen // Establece el rectangulo de donde coger la imagen
setSpriteClip(rect); spriteClip = {x, y, w, h};
// Inicializa variables // Inicializa variables
setEnabled(true); enabled = true;
} }
// Destructor // Destructor
Sprite::~Sprite() Sprite::~Sprite()
{ {
mTexture = nullptr; texture = nullptr;
mRenderer = nullptr; renderer = nullptr;
} }
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
void Sprite::render() void Sprite::render()
{ {
if (mEnabled) if (enabled)
{ {
mTexture->render(mRenderer, mPosX, mPosY, &mSpriteClip); texture->render(renderer, x, y, &spriteClip);
} }
} }
// Obten el valor de la variable // Obten el valor de la variable
int Sprite::getPosX() int Sprite::getPosX()
{ {
return mPosX; return x;
} }
// Obten el valor de la variable // Obten el valor de la variable
int Sprite::getPosY() int Sprite::getPosY()
{ {
return mPosY; return y;
} }
// Obten el valor de la variable // Obten el valor de la variable
int Sprite::getWidth() int Sprite::getWidth()
{ {
return mWidth; return w;
} }
// Obten el valor de la variable // Obten el valor de la variable
int Sprite::getHeight() int Sprite::getHeight()
{ {
return mHeight; return h;
}
// Establece la posición del objeto
void Sprite::setPos(SDL_Rect rect)
{
x = rect.x;
y = rect.y;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setPosX(int x) void Sprite::setPosX(int x)
{ {
mPosX = x; this->x = x;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setPosY(int y) void Sprite::setPosY(int y)
{ {
mPosY = y; this->y = y;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setWidth(int w) void Sprite::setWidth(int w)
{ {
mWidth = w; this->w = w;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setHeight(int h) void Sprite::setHeight(int h)
{ {
mHeight = h; this->h = h;
} }
// Obten el valor de la variable // Obten el valor de la variable
SDL_Rect Sprite::getSpriteClip() SDL_Rect Sprite::getSpriteClip()
{ {
return mSpriteClip; return spriteClip;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setSpriteClip(SDL_Rect rect) void Sprite::setSpriteClip(SDL_Rect rect)
{ {
mSpriteClip = rect; spriteClip = rect;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setSpriteClip(int x, int y, int w, int h) void Sprite::setSpriteClip(int x, int y, int w, int h)
{ {
mSpriteClip.x = x; spriteClip = {x, y, w, h};
mSpriteClip.y = y;
mSpriteClip.w = w;
mSpriteClip.h = h;
} }
// Obten el valor de la variable // Obten el valor de la variable
LTexture *Sprite::getTexture() LTexture *Sprite::getTexture()
{ {
return mTexture; return texture;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setTexture(LTexture *texture) void Sprite::setTexture(LTexture *texture)
{ {
mTexture = texture; this->texture = texture;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setRenderer(SDL_Renderer *renderer) void Sprite::setRenderer(SDL_Renderer *renderer)
{ {
mRenderer = renderer; this->renderer = renderer;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setEnabled(bool value) void Sprite::setEnabled(bool value)
{ {
mEnabled = value; enabled = value;
} }
// Comprueba si el objeto está habilitado // Comprueba si el objeto está habilitado
bool Sprite::isEnabled() bool Sprite::isEnabled()
{ {
return mEnabled; return enabled;
} }
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
SDL_Rect Sprite::getRect() SDL_Rect Sprite::getRect()
{ {
SDL_Rect rect = {getPosX(), getPosY(), getWidth(), getHeight()}; SDL_Rect rect = {x, y, w, h};
return rect; return rect;
}
// Establece los valores de posición y tamaño del sprite
void Sprite::setRect(SDL_Rect rect)
{
x = rect.x;
y = rect.y;
w = rect.w;
h = rect.h;
} }

View File

@@ -1,5 +1,6 @@
#pragma once #pragma once
#include "ifdefs.h"
#include <SDL2/SDL.h>
#include "ltexture.h" #include "ltexture.h"
#ifndef SPRITE_H #ifndef SPRITE_H
@@ -9,16 +10,16 @@
class Sprite class Sprite
{ {
protected: protected:
int mPosX; // Posición en el eje X donde dibujar el sprite int x; // Posición en el eje X donde dibujar el sprite
int mPosY; // Posición en el eje Y donde dibujar el sprite int y; // Posición en el eje Y donde dibujar el sprite
Uint16 mWidth; // Ancho del sprite int w; // Ancho del sprite
Uint16 mHeight; // Alto del sprite int h; // Alto del sprite
SDL_Renderer *mRenderer; // Puntero al renderizador de la ventana SDL_Renderer *renderer; // Puntero al renderizador de la ventana
LTexture *mTexture; // Textura donde estan todos los dibujos del sprite LTexture *texture; // Textura donde estan todos los dibujos del sprite
SDL_Rect mSpriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla SDL_Rect spriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla
bool mEnabled; // Indica si el sprite esta habilitado bool enabled; // Indica si el sprite esta habilitado
public: public:
// Constructor // Constructor
@@ -43,6 +44,9 @@ public:
// Obten el valor de la variable // Obten el valor de la variable
int getHeight(); int getHeight();
// Establece la posición del objeto
void setPos(SDL_Rect rect);
// Establece el valor de la variable // Establece el valor de la variable
void setPosX(int x); void setPosX(int x);
@@ -81,6 +85,9 @@ public:
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
SDL_Rect getRect(); SDL_Rect getRect();
// Establece los valores de posición y tamaño del sprite
void setRect(SDL_Rect rect);
}; };
#endif #endif