Trabajando en las colisiones con los enemigos

This commit is contained in:
2022-09-23 19:50:40 +02:00
parent eac0236c60
commit 48f84d28bd
21 changed files with 196 additions and 344 deletions

View File

@@ -57,7 +57,7 @@ void AnimatedSprite::animate()
// Si alcanza el final de la animación, reinicia 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 y coloca el nuevo frame // en función de la variable loop y coloca el nuevo frame
if (animation[currentAnimation].currentFrame >= animation[currentAnimation].frames.size()) if (animation[currentAnimation].currentFrame >= (int)animation[currentAnimation].frames.size())
{ {
if (animation[currentAnimation].loop == -1) if (animation[currentAnimation].loop == -1)
{ // Si no hay loop, deja el último frame { // Si no hay loop, deja el último frame
@@ -85,7 +85,7 @@ void AnimatedSprite::animate()
void AnimatedSprite::setCurrentFrame(int num) void AnimatedSprite::setCurrentFrame(int num)
{ {
// Descarta valores fuera de rango // Descarta valores fuera de rango
if (num >= animation[currentAnimation].frames.size()) if (num >= (int)animation[currentAnimation].frames.size())
{ {
num = 0; num = 0;
} }
@@ -170,7 +170,7 @@ bool AnimatedSprite::load(std::string filePath)
int pos = line.find("="); int pos = line.find("=");
// Procesa las dos subcadenas // Procesa las dos subcadenas
if (pos != line.npos) if (pos != (int)line.npos)
{ {
if (line.substr(0, pos) == "name") if (line.substr(0, pos) == "name")
{ {
@@ -217,7 +217,7 @@ bool AnimatedSprite::load(std::string filePath)
int pos = line.find("="); int pos = line.find("=");
// Procesa las dos subcadenas // Procesa las dos subcadenas
if (pos != line.npos) if (pos != (int)line.npos)
{ {
if (line.substr(0, pos) == "frames_per_row") if (line.substr(0, pos) == "frames_per_row")
{ {

View File

@@ -3,7 +3,7 @@
// Constructor // Constructor
Asset::Asset(std::string path) Asset::Asset(std::string path)
{ {
mExecutablePath = path; executablePath = path;
longest_name = 0; longest_name = 0;
} }
@@ -16,10 +16,10 @@ Asset::~Asset()
void Asset::add(std::string file, enum assetType type, bool required) void Asset::add(std::string file, enum assetType type, bool required)
{ {
item_t temp; item_t temp;
temp.file = mExecutablePath + "/.." + file; temp.file = executablePath + "/.." + file;
temp.type = type; temp.type = type;
temp.required = required; temp.required = required;
mFileList.push_back(temp); fileList.push_back(temp);
const std::string filename = file.substr(file.find_last_of("\\/") + 1); const std::string filename = file.substr(file.find_last_of("\\/") + 1);
longest_name = SDL_max(longest_name, filename.size()); longest_name = SDL_max(longest_name, filename.size());
@@ -28,9 +28,13 @@ void Asset::add(std::string file, enum assetType type, bool required)
// Devuelve el fichero de un elemento de la lista a partir de una cadena // Devuelve el fichero de un elemento de la lista a partir de una cadena
std::string Asset::get(std::string text) std::string Asset::get(std::string text)
{ {
for (int i = 0; i < mFileList.size(); i++) for (auto f : fileList)
if (mFileList[i].file.find(text) != std::string::npos) {
return mFileList[i].file; if (f.file.find(text) != std::string::npos)
{
return f.file;
}
}
printf("Warning: file %s not found\n", text.c_str()); printf("Warning: file %s not found\n", text.c_str());
return ""; return "";
@@ -44,31 +48,43 @@ bool Asset::check()
printf("\n** Checking files.\n"); printf("\n** Checking files.\n");
// Comprueba la lista de ficheros clasificandolos por tipo // Comprueba la lista de ficheros clasificandolos por tipo
for (int type = 0; type < maxAssetType; type++) for (int type = 0; type < maxAssetType; ++type)
{ {
// Comprueba si hay ficheros de ese tipo // Comprueba si hay ficheros de ese tipo
bool any = false; bool any = false;
for (int i = 0; i < mFileList.size(); i++) for (auto f : fileList)
if ((mFileList[i].required) && (mFileList[i].type == type)) {
if ((f.required) && (f.type == type))
{
any = true; any = true;
}
}
// Si hay ficheros de ese tipo, comprueba si existen // Si hay ficheros de ese tipo, comprueba si existen
if (any) if (any)
{ {
printf("\n>> %s FILES\n", getTypeName(type).c_str()); printf("\n>> %s FILES\n", getTypeName(type).c_str());
for (int i = 0; i < mFileList.size(); i++) for (auto f : fileList)
if ((mFileList[i].required) && (mFileList[i].type == type)) {
success &= checkFile(mFileList[i].file); if ((f.required) && (f.type == type))
{
success &= checkFile(f.file);
}
}
} }
} }
// Resultado // Resultado
if (success) if (success)
{
printf("\n** All files OK.\n\n"); printf("\n** All files OK.\n\n");
}
else else
{
printf("\n** A file is missing. Exiting.\n\n"); printf("\n** A file is missing. Exiting.\n\n");
}
return success; return success;
} }
@@ -104,30 +120,39 @@ std::string Asset::getTypeName(int type)
case bitmap: case bitmap:
return "BITMAP"; return "BITMAP";
break; break;
case music: case music:
return "MUSIC"; return "MUSIC";
break; break;
case sound: case sound:
return "SOUND"; return "SOUND";
break; break;
case font: case font:
return "FONT"; return "FONT";
break; break;
case lang: case lang:
return "LANG"; return "LANG";
break; break;
case data: case data:
return "DATA"; return "DATA";
break; break;
case room: case room:
return "ROOM"; return "ROOM";
break; break;
case enemy: case enemy:
return "ENEMY"; return "ENEMY";
break; break;
case item: case item:
return "ITEM"; return "ITEM";
break; break;
default: default:
return "ERROR"; return "ERROR";
break; break;

View File

@@ -35,8 +35,8 @@ private:
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<item_t> mFileList; std::vector<item_t> fileList;
std::string mExecutablePath; std::string executablePath;
// Comprueba que existe un fichero // Comprueba que existe un fichero
bool checkFile(std::string path); bool checkFile(std::string path);

View File

@@ -1,214 +0,0 @@
#include <cmath>
#include <map>
#include "easing.h"
#ifndef PI
#define PI 3.1415926545
#endif
double easeInSine( double t ) {
return sin( 1.5707963 * t );
}
double easeOutSine( double t ) {
return 1 + sin( 1.5707963 * (--t) );
}
double easeInOutSine( double t ) {
return 0.5 * (1 + sin( 3.1415926 * (t - 0.5) ) );
}
double easeInQuad( double t ) {
return t * t;
}
double easeOutQuad( double t ) {
return t * (2 - t);
}
double easeInOutQuad( double t ) {
return t < 0.5 ? 2 * t * t : t * (4 - 2 * t) - 1;
}
double easeInCubic( double t ) {
return t * t * t;
}
double easeOutCubic( double t ) {
return 1 + (--t) * t * t;
}
double easeInOutCubic( double t ) {
return t < 0.5 ? 4 * t * t * t : 1 + (--t) * (2 * (--t)) * (2 * t);
}
double easeInQuart( double t ) {
t *= t;
return t * t;
}
double easeOutQuart( double t ) {
t = (--t) * t;
return 1 - t * t;
}
double easeInOutQuart( double t ) {
if( t < 0.5 ) {
t *= t;
return 8 * t * t;
} else {
t = (--t) * t;
return 1 - 8 * t * t;
}
}
double easeInQuint( double t ) {
double t2 = t * t;
return t * t2 * t2;
}
double easeOutQuint( double t ) {
double t2 = (--t) * t;
return 1 + t * t2 * t2;
}
double easeInOutQuint( double t ) {
double t2;
if( t < 0.5 ) {
t2 = t * t;
return 16 * t * t2 * t2;
} else {
t2 = (--t) * t;
return 1 + 16 * t * t2 * t2;
}
}
double easeInExpo( double t ) {
return (pow( 2, 8 * t ) - 1) / 255;
}
double easeOutExpo( double t ) {
return 1 - pow( 2, -8 * t );
}
double easeInOutExpo( double t ) {
if( t < 0.5 ) {
return (pow( 2, 16 * t ) - 1) / 510;
} else {
return 1 - 0.5 * pow( 2, -16 * (t - 0.5) );
}
}
double easeInCirc( double t ) {
return 1 - sqrt( 1 - t );
}
double easeOutCirc( double t ) {
return sqrt( t );
}
double easeInOutCirc( double t ) {
if( t < 0.5 ) {
return (1 - sqrt( 1 - 2 * t )) * 0.5;
} else {
return (1 + sqrt( 2 * t - 1 )) * 0.5;
}
}
double easeInBack( double t ) {
return t * t * (2.70158 * t - 1.70158);
}
double easeOutBack( double t ) {
return 1 + (--t) * t * (2.70158 * t + 1.70158);
}
double easeInOutBack( double t ) {
if( t < 0.5 ) {
return t * t * (7 * t - 2.5) * 2;
} else {
return 1 + (--t) * t * 2 * (7 * t + 2.5);
}
}
double easeInElastic( double t ) {
double t2 = t * t;
return t2 * t2 * sin( t * PI * 4.5 );
}
double easeOutElastic( double t ) {
double t2 = (t - 1) * (t - 1);
return 1 - t2 * t2 * cos( t * PI * 4.5 );
}
double easeInOutElastic( double t ) {
double t2;
if( t < 0.45 ) {
t2 = t * t;
return 8 * t2 * t2 * sin( t * PI * 9 );
} else if( t < 0.55 ) {
return 0.5 + 0.75 * sin( t * PI * 4 );
} else {
t2 = (t - 1) * (t - 1);
return 1 - 8 * t2 * t2 * sin( t * PI * 9 );
}
}
double easeInBounce( double t ) {
return pow( 2, 6 * (t - 1) ) * abs( sin( t * PI * 3.5 ) );
}
double easeOutBounce( double t ) {
return 1 - pow( 2, -6 * t ) * abs( cos( t * PI * 3.5 ) );
}
double easeInOutBounce( double t ) {
if( t < 0.5 ) {
return 8 * pow( 2, 8 * (t - 1) ) * abs( sin( t * PI * 7 ) );
} else {
return 1 - 8 * pow( 2, -8 * t ) * abs( sin( t * PI * 7 ) );
}
}
easingFunction getEasingFunction( easing_functions function )
{
static std::map< easing_functions, easingFunction > easingFunctions;
if( easingFunctions.empty() )
{
easingFunctions.insert( std::make_pair( EaseInSine, easeInSine ) );
easingFunctions.insert( std::make_pair( EaseOutSine, easeOutSine ) );
easingFunctions.insert( std::make_pair( EaseInOutSine, easeInOutSine ) );
easingFunctions.insert( std::make_pair( EaseInQuad, easeInQuad ) );
easingFunctions.insert( std::make_pair( EaseOutQuad, easeOutQuad ) );
easingFunctions.insert( std::make_pair( EaseInOutQuad, easeInOutQuad ) );
easingFunctions.insert( std::make_pair( EaseInCubic, easeInCubic ) );
easingFunctions.insert( std::make_pair( EaseOutCubic, easeOutCubic ) );
easingFunctions.insert( std::make_pair( EaseInOutCubic, easeInOutCubic ) );
easingFunctions.insert( std::make_pair( EaseInQuart, easeInQuart ) );
easingFunctions.insert( std::make_pair( EaseOutQuart, easeOutQuart ) );
easingFunctions.insert( std::make_pair( EaseInOutQuart, easeInOutQuart) );
easingFunctions.insert( std::make_pair( EaseInQuint, easeInQuint ) );
easingFunctions.insert( std::make_pair( EaseOutQuint, easeOutQuint ) );
easingFunctions.insert( std::make_pair( EaseInOutQuint, easeInOutQuint ) );
easingFunctions.insert( std::make_pair( EaseInExpo, easeInExpo ) );
easingFunctions.insert( std::make_pair( EaseOutExpo, easeOutExpo ) );
easingFunctions.insert( std::make_pair( EaseInOutExpo, easeInOutExpo ) );
easingFunctions.insert( std::make_pair( EaseInCirc, easeInCirc ) );
easingFunctions.insert( std::make_pair( EaseOutCirc, easeOutCirc ) );
easingFunctions.insert( std::make_pair( EaseInOutCirc, easeInOutCirc ) );
easingFunctions.insert( std::make_pair( EaseInBack, easeInBack ) );
easingFunctions.insert( std::make_pair( EaseOutBack, easeOutBack ) );
easingFunctions.insert( std::make_pair( EaseInOutBack, easeInOutBack ) );
easingFunctions.insert( std::make_pair( EaseInElastic, easeInElastic ) );
easingFunctions.insert( std::make_pair( EaseOutElastic, easeOutElastic ) );
easingFunctions.insert( std::make_pair( EaseInOutElastic, easeInOutElastic ) );
easingFunctions.insert( std::make_pair( EaseInBounce, easeInBounce ) );
easingFunctions.insert( std::make_pair( EaseOutBounce, easeOutBounce ) );
easingFunctions.insert( std::make_pair( EaseInOutBounce, easeInOutBounce ) );
}
auto it = easingFunctions.find( function );
return it == easingFunctions.end() ? nullptr : it->second;
}

View File

@@ -1,40 +0,0 @@
#pragma once
enum easing_functions
{
EaseInSine,
EaseOutSine,
EaseInOutSine,
EaseInQuad,
EaseOutQuad,
EaseInOutQuad,
EaseInCubic,
EaseOutCubic,
EaseInOutCubic,
EaseInQuart,
EaseOutQuart,
EaseInOutQuart,
EaseInQuint,
EaseOutQuint,
EaseInOutQuint,
EaseInExpo,
EaseOutExpo,
EaseInOutExpo,
EaseInCirc,
EaseOutCirc,
EaseInOutCirc,
EaseInBack,
EaseOutBack,
EaseInOutBack,
EaseInElastic,
EaseOutElastic,
EaseInOutElastic,
EaseInBounce,
EaseOutBounce,
EaseInOutBounce
};
typedef double(*easingFunction)(double);
easingFunction getEasingFunction( easing_functions function );

View File

@@ -114,57 +114,84 @@ bool EnemyEngine::setEnemy(enemy_t *enemy, SDL_Point *p1, SDL_Point *p2, std::st
{ {
enemy->tileset = value; enemy->tileset = value;
} }
else if (var == "animation") else if (var == "animation")
{ {
enemy->animation = value; 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) * tile_size; enemy->x = std::stof(value) * tile_size;
} }
else if (var == "y") else if (var == "y")
{ {
enemy->y = std::stof(value) * tile_size; enemy->y = std::stof(value) * tile_size;
} }
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")
{ {
p1->x = std::stoi(value) * tile_size; p1->x = std::stoi(value) * tile_size;
} }
else if (var == "x2") else if (var == "x2")
{ {
p2->x = std::stoi(value) * tile_size; p2->x = std::stoi(value) * tile_size;
} }
else if (var == "y1") else if (var == "y1")
{ {
p1->y = std::stoi(value) * tile_size; p1->y = std::stoi(value) * tile_size;
} }
else if (var == "y2") else if (var == "y2")
{ {
p2->y = std::stoi(value) * tile_size; p2->y = std::stoi(value) * tile_size;
} }
else if (var == "[/path]") else if (var == "[/path]")
{ {
} }
else else
{ {
success = false; success = false;
} }
return success; return success;
}
// Comprueba las colisiones con los enemigos
bool EnemyEngine::checkEnemyCollision(SDL_Rect &rect)
{
for (auto enemy : enemies)
{
if (checkCollision(rect, enemy->getCollider()))
{
return true;
}
}
return false;
} }

View File

@@ -41,6 +41,9 @@ public:
// Actualiza las variables del objeto // Actualiza las variables del objeto
void update(); void update();
// Comprueba las colisiones con los enemigos
bool checkEnemyCollision(SDL_Rect &rect);
}; };
#endif #endif

View File

@@ -9,14 +9,14 @@ Game::Game(SDL_Renderer *renderer, Screen *screen, Asset *asset, Input *input, D
this->screen = screen; this->screen = screen;
this->input = input; this->input = input;
this->debug = debug; this->debug = debug;
//this->debug->setEnabled(true); this->debug->setEnabled(true);
// Reserva memoria para los objetos // Reserva memoria para los objetos
scoreboard = new ScoreBoard(renderer, asset, &board); scoreboard = new ScoreBoard(renderer, asset, &board);
eventHandler = new SDL_Event(); eventHandler = new SDL_Event();
itemTracker = new ItemTracker(); itemTracker = new ItemTracker();
map = new Map(asset->get("01.map"), renderer, asset, itemTracker); map = new Map(asset->get("01.map"), renderer, asset, itemTracker);
player = new Player(renderer, asset, input, map); player = new Player(renderer, asset, input, map, debug);
enemyEngine = new EnemyEngine(renderer, asset, player, map, asset->get(map->getEnemyFile())); enemyEngine = new EnemyEngine(renderer, asset, player, map, asset->get(map->getEnemyFile()));
music = JA_LoadMusic(asset->get("music_surface.ogg").c_str()); music = JA_LoadMusic(asset->get("music_surface.ogg").c_str());
@@ -93,14 +93,17 @@ void Game::update()
if (input->checkAnyInput()) if (input->checkAnyInput())
scoreboard->reset(); scoreboard->reset();
board.diamonds = player->diamonds;
// Actualiza los objetos // Actualiza los objetos
debug->clear(); debug->clear();
scoreboard->update(); scoreboard->update();
map->update(); map->update();
enemyEngine->update(); enemyEngine->update();
player->update(); player->update();
if (enemyEngine->checkEnemyCollision(player->getCollider()))
{
debug->add("COLLISION");
}
checkScreenBorders(); checkScreenBorders();
updateDebugInfo(); updateDebugInfo();
@@ -197,7 +200,7 @@ void Game::checkEventHandler()
delete map; delete map;
map = new Map(asset->get("01.map"), renderer, asset, itemTracker); map = new Map(asset->get("01.map"), renderer, asset, itemTracker);
delete player; delete player;
player = new Player(renderer, asset, input, map); player = new Player(renderer, asset, input, map, debug);
break; break;
case SDL_SCANCODE_F: case SDL_SCANCODE_F:
@@ -237,16 +240,6 @@ void Game::updateDebugInfo()
{ {
debug->add("R - Reload player and map"); debug->add("R - Reload player and map");
debug->add("D - Toggle debug mode"); debug->add("D - Toggle debug mode");
debug->add(std::to_string((int)player->sprite->getPosX()) + "," + std::to_string((int)player->sprite->getPosY()) + "," + std::to_string((int)player->sprite->getWidth()) + "," + std::to_string((int)player->sprite->getHeight()));
debug->add("VY " + std::to_string(player->vy) + " " + std::to_string(player->jumpStrenght));
debug->add("VX " + std::to_string(player->vx));
debug->add("jump_pressed " + std::to_string(player->jumpPressed));
debug->add("isOnFloor " + std::to_string(player->isOnFloor()));
debug->add("getTile(" + std::to_string(player->underFeet[0].x) + "," + std::to_string(player->underFeet[0].y) + ") = " + std::to_string(player->map->getTile(player->underFeet[0])));
debug->add("state " + std::to_string(player->state));
debug->add(map->getName() + " (" + map->getRoomFileName(b_top) + ", " + map->getRoomFileName(b_right) + ", " + map->getRoomFileName(b_bottom) + ", " + map->getRoomFileName(b_left) + ")");
debug->add("hookedOn = " + std::to_string(player->hookedOnMovingPlatform));
debug->add("DIAMONDS = " + std::to_string(player->diamonds));
} }
// Pone la información de debug en pantalla // Pone la información de debug en pantalla
@@ -270,7 +263,7 @@ void Game::renderDebugInfo()
// Pinta mascaras // Pinta mascaras
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 192); SDL_SetRenderDrawColor(renderer, 0, 255, 0, 192);
SDL_Rect rect = player->sprite->getRect(); SDL_Rect rect = player->getRect();
SDL_RenderFillRect(renderer, &rect); SDL_RenderFillRect(renderer, &rect);
// Pinta el texto // Pinta el texto

View File

@@ -34,8 +34,8 @@ private:
Debug *debug; // Objeto para gestionar la información de debug Debug *debug; // Objeto para gestionar la información de debug
SDL_Texture *spriteLayer; // Textura para dibujar los sprites SDL_Texture *spriteLayer; // Textura para dibujar los sprites
section_t section; // Seccion actual dentro del programa section_t section; // Seccion actual dentro del programa
int ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
int ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
bool musicEnabled; // Indica si la musica puede sonar o no bool musicEnabled; // Indica si la musica puede sonar o no
// Actualiza el juego, las variables, comprueba la entrada, etc. // Actualiza el juego, las variables, comprueba la entrada, etc.

View File

@@ -8,7 +8,7 @@ Input::Input(std::string file)
dbPath = file; dbPath = file;
// Inicializa las variables // Inicializa las variables
for (int i = 0; i < 17; i++) for (int i = 0; i < 17; ++i)
{ {
keyBindings[i].scancode = 0; keyBindings[i].scancode = 0;
keyBindings[i].active = false; keyBindings[i].active = false;
@@ -23,7 +23,7 @@ Input::Input(std::string file)
// Destructor // Destructor
Input::~Input() Input::~Input()
{ {
for (int i = 0; i < numGamepads; i++) for (int i = 0; i < numGamepads; ++i)
connectedControllers[i] = nullptr; connectedControllers[i] = nullptr;
} }
@@ -143,7 +143,7 @@ bool Input::checkAnyInput(int device, int index)
{ {
const Uint8 *mKeystates = SDL_GetKeyboardState(NULL); const Uint8 *mKeystates = SDL_GetKeyboardState(NULL);
for (int i = 0; i < 17; i++) for (int i = 0; i < 17; ++i)
{ {
if (mKeystates[keyBindings[i].scancode] != 0) if (mKeystates[keyBindings[i].scancode] != 0)
{ {
@@ -155,7 +155,7 @@ bool Input::checkAnyInput(int device, int index)
if (gameControllerFound()) if (gameControllerFound())
if ((device == INPUT_USE_GAMECONTROLLER) || (device == INPUT_USE_ANY)) if ((device == INPUT_USE_GAMECONTROLLER) || (device == INPUT_USE_ANY))
{ {
for (int i = 0; i < 17; i++) for (int i = 0; i < 17; ++i)
{ {
if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[i].button) != 0) if (SDL_GameControllerGetButton(connectedControllers[index], gameControllerBindings[i].button) != 0)
{ {
@@ -182,7 +182,7 @@ bool Input::discoverGameController()
numGamepads = 0; numGamepads = 0;
// Cuenta el numero de mandos // Cuenta el numero de mandos
for (int i = 0; i < nJoysticks; i++) for (int i = 0; i < nJoysticks; ++i)
if (SDL_IsGameController(i)) if (SDL_IsGameController(i))
numGamepads++; numGamepads++;
@@ -193,7 +193,7 @@ bool Input::discoverGameController()
{ {
found = true; found = true;
for (int i = 0; i < numGamepads; i++) for (int i = 0; i < numGamepads; ++i)
{ {
// Abre el mando y lo añade a la lista // Abre el mando y lo añade a la lista
SDL_GameController *pad = SDL_GameControllerOpen(i); SDL_GameController *pad = SDL_GameControllerOpen(i);

View File

@@ -22,8 +22,8 @@ private:
Asset *asset; // Objeto con los ficheros de recurso Asset *asset; // Objeto con los ficheros de recurso
AnimatedSprite *sprite; // Sprite para dibujar los graficos de la intro AnimatedSprite *sprite; // Sprite para dibujar los graficos de la intro
section_t section; // Estado del bucle principal para saber si continua o se sale section_t section; // Estado del bucle principal para saber si continua o se sale
int ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
int ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
// Actualiza las variables // Actualiza las variables
void update(); void update();

View File

@@ -57,31 +57,47 @@ void ItemTracker::addItem(std::string name, SDL_Point pos)
// Busca una entrada en la lista por nombre // Busca una entrada en la lista por nombre
int ItemTracker::findByName(std::string name) int ItemTracker::findByName(std::string name)
{ {
const int c = -1; /*for (int i = 0; i < list.size(); ++i)
for (int i = 0; i < list.size(); i++)
{ {
if (list[i].name == name) if (list[i].name == name)
{ {
return i; return i;
} }
}*/
int i = 0;
for (auto l : list)
{
if (l.name == name)
{
return i;
}
i++;
} }
return c; return -1;
} }
// Busca una entrada en la lista por posición // Busca una entrada en la lista por posición
int ItemTracker::findByPos(int index, SDL_Point pos) int ItemTracker::findByPos(int index, SDL_Point pos)
{ {
const int c = -1; /*for (int i = 0; i < list[index].pos.size(); ++i)
for (int i = 0; i < list[index].pos.size(); i++)
{ {
if ((list[index].pos[i].x == pos.x) && (list[index].pos[i].y == pos.y)) if ((list[index].pos[i].x == pos.x) && (list[index].pos[i].y == pos.y))
{ {
return i; return i;
} }
}*/
int i = 0;
for (auto l : list[index].pos)
{
if ((l.x == pos.x) && (l.y == pos.y))
{
return i;
}
i++;
} }
return c; return -1;
} }

View File

@@ -25,8 +25,8 @@ private:
Sprite *sprite; // Sprite con la textura del logo Sprite *sprite; // Sprite con la textura del logo
int counter; // Contador int counter; // Contador
section_t section; // Estado del bucle principal para saber si continua o se sale section_t section; // Estado del bucle principal para saber si continua o se sale
int ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
int ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int initFade; // Tiempo del contador cuando inicia el fade a negro int initFade; // Tiempo del contador cuando inicia el fade a negro
int endLogo; // Tiempo del contador para terminar el logo int endLogo; // Tiempo del contador para terminar el logo
int postLogo; // Tiempo que dura el logo con el fade al maximo int postLogo; // Tiempo que dura el logo con el fade al maximo

View File

@@ -92,7 +92,7 @@ bool Map::load(std::string file_path)
{ {
std::getline(file2, line); std::getline(file2, line);
pos = line.find("data encoding"); pos = line.find("data encoding");
} while (pos == std::string::npos); } while (pos == (int)std::string::npos);
do do
{ // Se introducen los valores separados por comas en un vector { // Se introducen los valores separados por comas en un vector
@@ -117,7 +117,7 @@ bool Map::load(std::string file_path)
{ {
std::getline(file2, line); std::getline(file2, line);
pos = line.find("data encoding"); pos = line.find("data encoding");
} while (pos == std::string::npos); } while (pos == (int)std::string::npos);
do do
{ // Se introducen los valores separados por comas en un vector { // Se introducen los valores separados por comas en un vector
@@ -142,7 +142,7 @@ bool Map::load(std::string file_path)
{ {
std::getline(file2, line); std::getline(file2, line);
pos = line.find("data encoding"); pos = line.find("data encoding");
} while (pos == std::string::npos); } while (pos == (int)std::string::npos);
do do
{ // Se introducen los valores separados por comas en un vector { // Se introducen los valores separados por comas en un vector
@@ -438,7 +438,7 @@ void Map::fillMapTexture()
// Dibuja el degradado de fondo // Dibuja el degradado de fondo
const float num_lines = PLAY_AREA_BOTTOM - PLAY_AREA_TOP; const float num_lines = PLAY_AREA_BOTTOM - PLAY_AREA_TOP;
for (int i = PLAY_AREA_TOP; i < PLAY_AREA_BOTTOM; i++) for (int i = PLAY_AREA_TOP; i < PLAY_AREA_BOTTOM; ++i)
{ {
float step = ((float)i / num_lines); float step = ((float)i / num_lines);
int r = bgColor1.r + ((bgColor2.r - bgColor1.r) * step); int r = bgColor1.r + ((bgColor2.r - bgColor1.r) * step);
@@ -449,8 +449,8 @@ void Map::fillMapTexture()
} }
// Dibuja el mapeado de tiles // Dibuja el mapeado de tiles
for (int y = 0; y < map_height; y++) for (int y = 0; y < map_height; ++y)
for (int x = 0; x < map_width; x++) for (int x = 0; x < map_width; ++x)
{ {
// Resta uno porque Tiled almacena los indices empezando de 1 en vez de 0. // Resta uno porque Tiled almacena los indices empezando de 1 en vez de 0.
// El problema es que los tiles vacios los pone como 0 y aqui pasan a ser -1 // El problema es que los tiles vacios los pone como 0 y aqui pasan a ser -1
@@ -469,8 +469,8 @@ void Map::fillMapTexture()
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
// Dibuja el mapeado de tiles // Dibuja el mapeado de tiles
for (int y = 0; y < map_height; y++) for (int y = 0; y < map_height; ++y)
for (int x = 0; x < map_width; x++) for (int x = 0; x < map_width; ++x)
{ {
// Resta uno porque Tiled almacena los indices empezando de 1 en vez de 0. // Resta uno porque Tiled almacena los indices empezando de 1 en vez de 0.
// El problema es que los tiles vacios los pone como 0 y aqui pasan a ser -1 // El problema es que los tiles vacios los pone como 0 y aqui pasan a ser -1
@@ -511,8 +511,8 @@ void Map::renderLayer0()
} }
else else
{ {
SDL_Rect rect = {PLAY_AREA_X, PLAY_AREA_Y, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT}; //SDL_Rect rect = {PLAY_AREA_X, PLAY_AREA_Y, PLAY_AREA_WIDTH, PLAY_AREA_HEIGHT};
SDL_RenderCopy(renderer, map_layer0, nullptr, nullptr); SDL_RenderCopy(renderer, map_layer0, NULL, NULL);
} }
} }

View File

@@ -451,7 +451,7 @@ void Menu::updateSelector()
// Coloca el selector en una posición específica // Coloca el selector en una posición específica
void Menu::setSelectorPos(int index) void Menu::setSelectorPos(int index)
{ {
if (index < item.size()) if (index < (int)item.size())
{ {
selector.index = index; selector.index = index;
selector.rect.y = selector.y = selector.originY = selector.targetY = item[selector.index].rect.y; selector.rect.y = selector.y = selector.originY = selector.targetY = item[selector.index].rect.y;
@@ -615,8 +615,8 @@ void Menu::render()
SDL_RenderDrawRect(renderer, &rectBG.rect); SDL_RenderDrawRect(renderer, &rectBG.rect);
} }
// Renderitza el texto // Renderiza el texto
for (int i = 0; i < item.size(); i++) for (int i = 0; i < (int)item.size(); ++i)
{ {
if (i == selector.index) if (i == selector.index)
{ {
@@ -852,7 +852,7 @@ void Menu::replaceElementsOnY()
{ {
item[0].rect.y = y; item[0].rect.y = y;
for (int i = 1; i < item.size(); i++) for (int i = 1; i < (int)item.size(); i++)
{ {
item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown; item[i].rect.y = item[i - 1].rect.y + item[i - 1].rect.h + item[i - 1].hPaddingDown;
} }

View File

@@ -1,12 +1,13 @@
#include "player.h" #include "player.h"
// Constructor // Constructor
Player::Player(SDL_Renderer *renderer, Asset *asset, Input *input, Map *map) Player::Player(SDL_Renderer *renderer, Asset *asset, Input *input, Map *map, Debug *debug)
{ {
this->asset = asset; this->asset = asset;
this->renderer = renderer; this->renderer = renderer;
this->input = input; this->input = input;
this->map = map; this->map = map;
this->debug = debug;
sound_jump = JA_LoadSound(asset->get("sound_player_jump.wav").c_str()); sound_jump = JA_LoadSound(asset->get("sound_player_jump.wav").c_str());
sound_death = JA_LoadSound(asset->get("sound_player_death.wav").c_str()); sound_death = JA_LoadSound(asset->get("sound_player_death.wav").c_str());
@@ -40,6 +41,7 @@ Player::Player(SDL_Renderer *renderer, Asset *asset, Input *input, Map *map)
underFeet.insert(underFeet.end(), {p, p, p}); underFeet.insert(underFeet.end(), {p, p, p});
hookedOnMovingPlatform = -1; hookedOnMovingPlatform = -1;
diamonds = 0; diamonds = 0;
colliderBox = getRect();
} }
// Destructor // Destructor
@@ -62,6 +64,18 @@ void Player::update()
move(); move();
animate(); animate();
checkActors(); checkActors();
colliderBox = getRect();
debug->add(std::to_string((int)sprite->getPosX()) + "," + std::to_string((int)sprite->getPosY()) + "," + std::to_string((int)sprite->getWidth()) + "," + std::to_string((int)sprite->getHeight()));
debug->add("VY " + std::to_string(vy) + " " + std::to_string(jumpStrenght));
debug->add("VX " + std::to_string(vx));
debug->add("jump_pressed " + std::to_string(jumpPressed));
debug->add("isOnFloor " + std::to_string(isOnFloor()));
debug->add("getTile(" + std::to_string(underFeet[0].x) + "," + std::to_string(underFeet[0].y) + ") = " + std::to_string(map->getTile(underFeet[0])));
debug->add("state " + std::to_string(state));
debug->add(map->getName() + " (" + map->getRoomFileName(b_top) + ", " + map->getRoomFileName(b_right) + ", " + map->getRoomFileName(b_bottom) + ", " + map->getRoomFileName(b_left) + ")");
debug->add("hookedOn = " + std::to_string(hookedOnMovingPlatform));
debug->add("DIAMONDS = " + std::to_string(diamonds));
} }
// Dibuja el objeto // Dibuja el objeto
@@ -75,23 +89,27 @@ void Player::checkInput()
{ {
if (input->checkInput(INPUT_LEFT, REPEAT_TRUE)) if (input->checkInput(INPUT_LEFT, REPEAT_TRUE))
{ {
vx = std::max(vx -= accelX, -maxVX); vx -= accelX;
vx = std::max(vx, -maxVX);
sprite->setFlip(SDL_FLIP_HORIZONTAL); sprite->setFlip(SDL_FLIP_HORIZONTAL);
} }
else if (input->checkInput(INPUT_RIGHT, REPEAT_TRUE)) else if (input->checkInput(INPUT_RIGHT, REPEAT_TRUE))
{ {
vx = std::min(vx += accelX, maxVX); vx += accelX;
vx = std::min(vx, maxVX);
sprite->setFlip(SDL_FLIP_NONE); sprite->setFlip(SDL_FLIP_NONE);
} }
else else
{ {
if (vx > 0.0f) if (vx > 0.0f)
{ {
vx = std::max(vx -= accelX, 0.0f); vx -= accelX;
vx = std::max(vx, 0.0f);
} }
else else
{ {
vx = std::min(vx += accelX, 0.0f); vx += accelX;
vx = std::min(vx, 0.0f);
} }
} }
@@ -113,7 +131,8 @@ void Player::checkInput()
{ {
if (jumpPressed) if (jumpPressed)
{ {
jumpStrenght = std::max(jumpStrenght -= 0.4f, 0.0f); jumpStrenght -= 0.4f;
jumpStrenght = std::max(jumpStrenght, 0.0f);
vy -= jumpStrenght; vy -= jumpStrenght;
} }
} }
@@ -139,7 +158,8 @@ void Player::addGravity()
// *** Falta ver pq la gravedad empuja al muñeco hacia abajo en los tiles atravesables // *** Falta ver pq la gravedad empuja al muñeco hacia abajo en los tiles atravesables
if (state != s_standing) if (state != s_standing)
{ {
vy = std::min(vy += gravity, maxVY); vy += gravity;
vy = std::min(vy, maxVY);
} }
} }
@@ -397,31 +417,33 @@ bool Player::isOnMovingPlatform()
// Comprueba si está situado en alguno de los cuatro bordes de la habitación // Comprueba si está situado en alguno de los cuatro bordes de la habitación
bool Player::isOnScreenBorder() bool Player::isOnScreenBorder()
{ {
bool success = false;
border = b_none; border = b_none;
if (x < map->getPlayArea(b_left)) if (x < map->getPlayArea(b_left))
{ {
border = b_left; border = b_left;
success = true; return true;
} }
else if (x > map->getPlayArea(b_right) - w) else if (x > map->getPlayArea(b_right) - w)
{ {
border = b_right; border = b_right;
success = true; return true;
} }
else if (y < map->getPlayArea(b_top)) else if (y < map->getPlayArea(b_top))
{ {
border = b_top; border = b_top;
success = true; return true;
} }
else if (y > map->getPlayArea(b_bottom) - h) else if (y > map->getPlayArea(b_bottom) - h)
{ {
border = b_bottom; border = b_bottom;
success = true; return true;
} }
return success; return false;
} }
// Devuelve el valor de la variable // Devuelve el valor de la variable
@@ -486,4 +508,16 @@ int Player::checkActors()
void Player::reLoadTextures() void Player::reLoadTextures()
{ {
texture->reLoad(); texture->reLoad();
}
// Devuelve el rectangulo que contiene al enemigo
SDL_Rect Player::getRect()
{
return sprite->getRect();
}
// Obtiene el rectangulo de colision del enemigo
SDL_Rect &Player::getCollider()
{
return colliderBox;
} }

View File

@@ -8,6 +8,7 @@
#include "asset.h" #include "asset.h"
#include "map.h" #include "map.h"
#include "actor.h" #include "actor.h"
#include "debug.h"
#ifndef PLAYER_H #ifndef PLAYER_H
#define PLAYER_H #define PLAYER_H
@@ -29,13 +30,14 @@ enum e_floor
// The player // The player
class Player class Player
{ {
public: private:
Asset *asset; // Objeto con la ruta a todos los ficheros de recursos Asset *asset; // Objeto con la ruta a todos los ficheros de recursos
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
Input *input; // Objeto Input para gestionar las entradas Input *input; // Objeto Input para gestionar las entradas
AnimatedSprite *sprite; // Objeto con los graficos, animaciones y posición del jugador AnimatedSprite *sprite; // Objeto con los graficos, animaciones y posición del jugador
LTexture *texture; // Textura con los graficos del jugador LTexture *texture; // Textura con los graficos del jugador
Map *map; // Objeto con el mapa Map *map; // Objeto con el mapa
Debug *debug; // Objeto para gestionar la información de debug
float x; // Posición del jugador en el eje X float x; // Posición del jugador en el eje X
float y; // Posición del jugador en el eje Y float y; // Posición del jugador en el eje Y
@@ -48,6 +50,7 @@ public:
SDL_Point lastPosition; // Posición anterior SDL_Point lastPosition; // Posición anterior
int hookedOnMovingPlatform; // Índice de la plataforma movil a la que está enganchado int hookedOnMovingPlatform; // Índice de la plataforma movil a la que está enganchado
e_floor isOn; // Indica sobre que tipo de suelo se encuentra e_floor isOn; // Indica sobre que tipo de suelo se encuentra
SDL_Rect colliderBox; // Caja de colisión
// Variables que afectan a la inercia del movimiento // Variables que afectan a la inercia del movimiento
bool jumpPressed; // Indica si esta pulsada la tecla de salto bool jumpPressed; // Indica si esta pulsada la tecla de salto
@@ -97,7 +100,7 @@ public:
public: public:
// Constructor // Constructor
Player(SDL_Renderer *renderer, Asset *asset, Input *input, Map *map); Player(SDL_Renderer *renderer, Asset *asset, Input *input, Map *map, Debug *debug);
// Destructor // Destructor
~Player(); ~Player();
@@ -122,6 +125,12 @@ public:
// Recarga las texturas // Recarga las texturas
void reLoadTextures(); void reLoadTextures();
// Devuelve el rectangulo que contiene al jugador
SDL_Rect getRect();
// Obtiene el rectangulo de colision del jugador
SDL_Rect &getCollider();
}; };
#endif #endif

View File

@@ -54,7 +54,7 @@ void ScoreBoard::fillTexture()
// Pinta el degradado // Pinta el degradado
const float num_lines = (SCOREBOARD_BOTTOM / 2) - SCOREBOARD_TOP; const float num_lines = (SCOREBOARD_BOTTOM / 2) - SCOREBOARD_TOP;
for (int i = SCOREBOARD_TOP; i < SCOREBOARD_TOP + num_lines; i++) for (int i = SCOREBOARD_TOP; i < SCOREBOARD_TOP + num_lines; ++i)
{ {
float step = ((float)i / num_lines); float step = ((float)i / num_lines);
int alpha = 64 + ((0 - 64) * step); int alpha = 64 + ((0 - 64) * step);

View File

@@ -6,7 +6,6 @@
#include "asset.h" #include "asset.h"
#include "sprite.h" #include "sprite.h"
#include "const.h" #include "const.h"
#include "easing.h"
#include <string> #include <string>
#ifndef SCOREBOARD_H #ifndef SCOREBOARD_H

View File

@@ -26,7 +26,7 @@ Text::~Text()
void Text::init() void Text::init()
{ {
// Inicializa a cero el vector con las coordenadas // Inicializa a cero el vector con las coordenadas
for (int i = 0; i < 128; i++) for (int i = 0; i < 128; ++i)
{ {
offset[i].x = 0; offset[i].x = 0;
offset[i].y = 0; offset[i].y = 0;
@@ -44,7 +44,7 @@ void Text::init()
sprite->setSpriteClip(0, 0, sprite->getWidth(), sprite->getHeight()); sprite->setSpriteClip(0, 0, sprite->getWidth(), sprite->getHeight());
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho // Establece las coordenadas para cada caracter ascii de la cadena y su ancho
for (int i = 32; i < 128; i++) for (int i = 32; i < 128; ++i)
{ {
offset[i].x = ((i - 32) % 15) * boxWidth; offset[i].x = ((i - 32) % 15) * boxWidth;
offset[i].y = ((i - 32) / 15) * boxHeight; offset[i].y = ((i - 32) / 15) * boxHeight;
@@ -131,7 +131,7 @@ int Text::lenght(std::string text, int kerning)
{ {
int shift = 0; int shift = 0;
for (int i = 0; i < (int)text.length(); i++) for (int i = 0; i < (int)text.length(); ++i)
shift += (offset[int(text[i])].w + kerning); shift += (offset[int(text[i])].w + kerning);
// Descuenta el kerning del último caracter // Descuenta el kerning del último caracter

View File

@@ -29,8 +29,8 @@ private:
AnimatedSprite *sprite; // Sprite para dibujar los graficos de la intro AnimatedSprite *sprite; // Sprite para dibujar los graficos de la intro
JA_Music music; // Musica del titulo del juego JA_Music music; // Musica del titulo del juego
section_t section; // Estado del bucle principal para saber si continua o se sale section_t section; // Estado del bucle principal para saber si continua o se sale
int ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
int ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
// Actualiza las variables // Actualiza las variables
void update(); void update();