I've been trying to make a lightweight template for myself using sprites and eventually physics. For now, I created this Sprite Manager:
class SpriteManager{
public:
SpriteManager();
~SpriteManager();
void addImage(std::string file);
sf::Image* getImage(std::string file) { return Images.find(file)->second; }
void addSprite(std::string file, std::string id); // returns a pointer to created sprite
sf::Sprite* getSprite(std::string id) { return Sprites.find(id)->second; };
void update();
private:
std::map<std::string, sf::Sprite*> Sprites; // id, sprite
std::map<std::string, sf::Image*> Images; // file name, image
};
SpriteManager::SpriteManager(){
}
SpriteManager::~SpriteManager(){
std::map<std::string, sf::Sprite*>::iterator it1 = Sprites.begin();
while(it1 != Sprites.end())
Sprites.erase(it1++);
std::map<std::string, sf::Image*>::iterator it2 = Images.begin();
while(it2 != Images.end())
Images.erase(it2++);
}
void SpriteManager::addImage(std::string file){
if(Images.find(file) == Images.end()){ // If image is not in map already.
std::cout << "Adding image " << file << std::endl;
sf::Image* image = new sf::Image();
if(image->LoadFromFile(file))
Images.insert(std::pair<std::string, sf::Image*>(file, image));
else
std::cout << "Image was unable to be loaded" << std::endl;
}
else{
std::cout << "Image " << file << " was already loaded" << std::endl;
}
}
void SpriteManager::addSprite(std::string file, std::string id){
addImage(file);
sf::Sprite* sprite = new sf::Sprite(*getImage(file));
Sprites.insert(std::pair<std::string, sf::Sprite*>(id, sprite));
}
void SpriteManager::update(){
for(std::map<std::string, sf::Sprite*>::iterator it = Sprites.begin();
it != Sprites.end(); it++)
g_App->Draw(*(*it).second);
}
This can be used by creating sprites like so:
// Initialize the Sprite Manager
g_SpriteManager = new SpriteManager();
// Create the sprites
g_SpriteManager->addImage("./res/Harlem.png");
g_SpriteManager->addSprite("./res/Harlem.png", "Harlem");
g_SpriteManager->addImage("./res/dot.png");
g_SpriteManager->addSprite("./res/dot.png", "dot1");
sf::Sprite* testSprite = g_SpriteManager->getSprite("dot1");
testSprite->SetPosition(30.f, 53.f);
And then you call it by using:
g_SpriteManager->update();
I'd like to know what all of you think of this. Let me know if you have any critiques of my code