5
« on: April 23, 2021, 03:51:54 am »
Hi everyone. i have a problem. I learn to coding and making little projects for improving my skills. I wrote a code like this:
//enemy class
class enemy {
public:
sf::RectangleShape rect;
float bottom, left, right, top;
bool touch = false;
sf::Sprite itemss;
sf::Texture enemyt;
enemy(sf::Vector2f position, sf::Vector2f size, sf::Color color) {
rect.setPosition(position);
rect.setSize(size);
rect.setFillColor(color);
enemyt.loadFromFile("inv/invpouch.png");
enemys.setTexture(enemyt);
}
void kill()
{
std::cout << "Killing Enemy >> " << std::endl;
}
~enemy() {
}
void update() {
bottom = rect.getPosition().y + rect.getSize().y;
left = rect.getPosition().x;
right = rect.getPosition().x + rect.getSize().x;
top = rect.getPosition().y;
if (right > recx && left < recx + 30 && top < recy + 30 && bottom > recy) {
enemys.setColor(sf::Color(255, 255, 255, 155));
}
}
bool collision(enemy e) {
if (right < e.left || left > e.right || top > e.bottom || bottom < e.top) {
return false;
}
return true;
}
};
//create enemies
std::vector <enemy*> enemies1;
for (unsigned i = 0; i < 5; ++i) {
enemies1.push_back(new enemy(sf::Vector2f(100 * i + 800, 500), sf::Vector2f(15, 10), sf::Color(255, 255, 255, 0)));
}
//update
for (unsigned i = 0; i < 5; ++i) {
enemies1->update();
}
if (!enemies1.empty()){
enemies1.erase(std::remove_if(enemies1.begin(), enemies1.end(), [](const auto &itr) {return itr->touch; }), enemies1.end());
}
//render
for (unsigned i = 0; i < 5; ++i) {
window.draw(enemies1->enemysprite);
}
my goal is erase some enemies. with this code i can do that but problem is that
1- i cant erase last enemy of enemies1 vector. 1,2,3,4th values are erasing but not number 5(array no 4)
2- Using vectors Is a good way for create and delete enemies because in my game there will be some npc's and they will spawn, die and they will have their own stats and such.
I appreciate for every advice.