So this is a function I call in my main function in my 'main.cpp' which returns a vector of object of the 'Star' class:
std::vector<Star> generateStars(int numOfStars,int thresh)
{
std::vector<Star> stars;
//does some stuff with the vector 'stars'
return stars;
};
My 'Star' class inherits from 'sf::Sprite' as such:
class Star : public sf::Sprite
{
private:
void Init(int xCoord,int yCoord)
{
setPosition(xCoord,yCoord);
}
public:
int xPos;
int yPos;
Star(int inX, int inY)
{
xPos = inX;
yPos = inY;
Init(xPos,yPos);
}
};
I obviously then want to assign a texture to each 'Star' object in my vector of 'Star' objects and then draw each, so I thought I would implement it as such:
int main(int, char const**)
{
// Create the main window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML window");
// Set the Icon
sf::Image icon;
if (!icon.loadFromFile(resourcePath() + "icon.png")) {
return EXIT_FAILURE;
}
window.setIcon(icon.getSize().x, icon.getSize().y, icon.getPixelsPtr());
// Load a sprite to display
sf::Texture texture;
if (!texture.loadFromFile(resourcePath() + "Untitled-1.png")) {
return EXIT_FAILURE; //was "cute_image.jpg"
}
std::vector<Star> starsVec = generateStars(20,20);
for(Star iter : starsVec)
{
iter.setTexture(texture);
}
// Start the game loop
while (window.isOpen())
{
// Process events
sf::Event event;
while (window.pollEvent(event))
{
// Close window : exit
if (event.type == sf::Event::Closed) {
window.close();
}
// Espace pressed : exit
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
window.close();
}
}
// Clear screen
window.clear();
// Draw the sprite
for(Star it : starsVec)
{
window.draw(it);
}
// Update the window
window.display();
}
return EXIT_SUCCESS;
}
This returns a blank window, so I'm assuming that my calls to 'setTexture' and 'draw' are being destroyed after the loops which iterate through my vector ends. If this is a correct assumption, how would I rewrite my code so that this does not happen?