Finally I'm implementig the std::vector (after having done some console experiments, which have shown, that it indeed has a better functionality) and there is no error so far, but I don't know what to do for removing only one sprite at a time instead of all sprites. I know that the struct is incomplete and always set to "true" (probably will need an additioanal bool) , but what additional argument to put inside it for it to work properly. Any hints?
#include <SFML/Graphics.hpp>
#include <iostream>
#include <vector>
#include <algorithm>
struct IsUnitRemoved {
bool operator() (const sf::Sprite& e) const {
return 1;
}
};
int main()
{
sf::RenderWindow mMainWindow(sf::VideoMode(1200, 900), "Window");
mMainWindow.setFramerateLimit(60);
sf::Image image;
image.create(50, 50, sf::Color::Red);
sf::Texture texture;
texture.loadFromImage(image);
std::vector<sf::Sprite> SpriteVector;
std::vector<sf::Sprite>::iterator SpriteIt;
while (mMainWindow.isOpen())
{
sf::Event event;
bool creating = false;
bool rightclick = false;
sf::Vector2i mousePos;
while (mMainWindow.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
mMainWindow.close();
break;
case sf::Event::KeyPressed:
creating = (event.key.code == sf::Keyboard::A);
break;
case sf::Event::MouseButtonPressed:
if (event.mouseButton.button == sf::Mouse::Right)
rightclick = true;
mousePos = sf::Vector2i (event.mouseButton.x, event.mouseButton.y);
break;
}
}
if (creating)
{
sf::Sprite newSprite;
newSprite.setTexture(texture);
newSprite.setPosition(mMainWindow.mapPixelToCoords(sf::Vector2i(sf::Mouse::getPosition(mMainWindow).x-50,sf::Mouse::getPosition(mMainWindow).y-50)));
SpriteVector.push_back(newSprite);
}
if (rightclick)
{
for(SpriteIt = SpriteVector.begin();SpriteIt != SpriteVector.end(); )
{
sf::Vector2f mousecoords(mMainWindow.mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y)));
if(SpriteIt->getGlobalBounds().contains(mousecoords))
{
SpriteIt = SpriteVector.erase(std::remove_if(SpriteVector.begin(), SpriteVector.end(), IsUnitRemoved()),SpriteVector.end());
}
else
{
++SpriteIt;
}
}
}
mMainWindow.clear();
for(auto &SpriteIt = SpriteVector.begin();SpriteIt != SpriteVector.end();++SpriteIt)
{
mMainWindow.draw(*SpriteIt);
}
mMainWindow.display();
}
return 0;
}