AnimatedSprite::getIndex() ara gasta un std::unordered_map

This commit is contained in:
2025-07-11 23:10:50 +02:00
parent 66d55061dd
commit 06815d4f72
2 changed files with 14 additions and 8 deletions

View File

@@ -55,20 +55,19 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const Animation
// Obtiene el índice de la animación a partir del nombre // Obtiene el índice de la animación a partir del nombre
int AnimatedSprite::getIndex(const std::string &name) int AnimatedSprite::getIndex(const std::string &name)
{ {
auto index = -1; auto it = animation_indices_.find(name);
if (it != animation_indices_.end())
{
// Si se encuentra la animación en el mapa, devuelve su índice
return it->second;
}
for (const auto &a : animations_) // Si no se encuentra, muestra una advertencia y devuelve -1
{
index++;
if (a.name == name)
{
return index;
}
}
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "** Warning: could not find \"%s\" animation", name.c_str()); SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "** Warning: could not find \"%s\" animation", name.c_str());
return -1; return -1;
} }
// Calcula el frame correspondiente a la animación // Calcula el frame correspondiente a la animación
void AnimatedSprite::animate() void AnimatedSprite::animate()
{ {
@@ -257,6 +256,9 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so
// Añade la animación al vector de animaciones // Añade la animación al vector de animaciones
animations_.emplace_back(animation); animations_.emplace_back(animation);
// Rellena el mapa con el nombre y el nuevo índice
animation_indices_[animation.name] = animations_.size() - 1;
} }
// Una vez procesada la línea, aumenta el índice para pasar a la siguiente // Una vez procesada la línea, aumenta el índice para pasar a la siguiente

View File

@@ -4,6 +4,7 @@
#include <memory> #include <memory>
#include <string> #include <string>
#include <vector> #include <vector>
#include <unordered_map>
#include "moving_sprite.h" #include "moving_sprite.h"
@@ -58,6 +59,9 @@ protected:
std::vector<Animation> animations_; // Vector de animaciones disponibles std::vector<Animation> animations_; // Vector de animaciones disponibles
int current_animation_ = 0; // Índice de la animación activa int current_animation_ = 0; // Índice de la animación activa
// --- Mapa para búsqueda rápida de animaciones por nombre ---
std::unordered_map<std::string, int> animation_indices_;
// --- Métodos internos --- // --- Métodos internos ---
void animate(); // Calcula el frame actual de la animación void animate(); // Calcula el frame actual de la animación
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source); // Carga animaciones desde un buffer void loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source); // Carga animaciones desde un buffer