diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index bf7b2ab..8a41ac1 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -55,20 +55,19 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr texture, const Animation // Obtiene el índice de la animación a partir del nombre int AnimatedSprite::getIndex(const std::string &name) { - auto index = -1; - - for (const auto &a : animations_) + auto it = animation_indices_.find(name); + if (it != animation_indices_.end()) { - index++; - if (a.name == name) - { - return index; - } + // Si se encuentra la animación en el mapa, devuelve su índice + return it->second; } + + // Si no se encuentra, muestra una advertencia y devuelve -1 SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "** Warning: could not find \"%s\" animation", name.c_str()); return -1; } + // Calcula el frame correspondiente a la animación void AnimatedSprite::animate() { @@ -257,6 +256,9 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &so // Añade la animación al vector de animaciones 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 diff --git a/source/animated_sprite.h b/source/animated_sprite.h index 9d97576..5054b9d 100644 --- a/source/animated_sprite.h +++ b/source/animated_sprite.h @@ -4,6 +4,7 @@ #include #include #include +#include #include "moving_sprite.h" @@ -58,6 +59,9 @@ protected: std::vector animations_; // Vector de animaciones disponibles int current_animation_ = 0; // Índice de la animación activa + // --- Mapa para búsqueda rápida de animaciones por nombre --- + std::unordered_map animation_indices_; + // --- Métodos internos --- void animate(); // Calcula el frame actual de la animación void loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source); // Carga animaciones desde un buffer