I'm trying to make a vector of all drawables so that I can make a simple render routine that just loops through all drawable objects and draws them. Here are some of the relevant bits of my code:
Declaring the vector:
std::vector<sf::Drawable*> drawables;
Looping through the enemies and adding them to the vector:
for (enemy_main::Enemy& enemy : enemies)
{
drawables.emplace_back(enemy.getSprite());
drawables.emplace_back(enemy.getRedRectnagle());
drawables.emplace_back(enemy.getHealthRectangle());
}
In my Enemy class, here are the accessors you see in the code above:
sf::Sprite& getSprite() { return sprite; }
sf::RectangleShape& getHealthRectangle() { return healthRectangle; }
sf::RectangleShape& getRedRectnagle() { return redRectangle; }
And finally the drawing:
for (auto const& drawable : drawables)
{
myWindow.draw(*drawable);
}
What I'm getting when I try to build are the following errors:
Error C2440 'initializing': cannot convert from 'sf::Sprite' to 'sf::Drawable *' TestSFML c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\xmemory0 918
Error C2440 'initializing': cannot convert from 'sf::Sprite' to 'sf::Drawable *' TestSFML c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\vector 1035
Error C2440 'initializing': cannot convert from 'sf::RectangleShape' to 'sf::Drawable *' TestSFML c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\xmemory0 918
The errors are pointing to libraries that I didn't obviously write, but the error isn't in those libraries. That much is obvious to me. What's not obvious to me is what's wrong with my code where
What about making Enemy a Drawable itself, and write window.draw(enemy), rather than adding all those accessors? That would make it much more encapsulated, readable and maintainable.
Excellent suggestion. Now I can:
Add an enemy directly to the drawables vector:
for (enemy_main::Enemy& enemy : enemies)
{
drawables.emplace_back(&enemy);
}
Draw all of my drawable objects:
for (sf::Drawable* const drawable : drawables)
{
myWindow.draw(*drawable);
}