0

I am doing a Space Invaders game for a project in SFML, and I have had problem, because I check the collision of the Bullet with the Enemy and it works as it should, until there is one Bullet type object inside the container, when there are already two or more and a collision occurs, I am getting the error "Unhandled Exception at 0x00007FFF7BA9DD7E (ucrtbase.dll) in SI.exe: Fatal Exit Request.". I suspect the problem is with the iterator here as the amount of objects in the container is variable.

void Bullet::hit(vector<Enemy>& enemies,vector<Pixel>& oneShield, vector<Bullet>& bullets, int &killedEnemies, int shotsFired) {
    for (auto& enemy : enemies) {
        if (enemy.shape.getGlobalBounds().intersects(this->shape.getGlobalBounds())) {
            for (auto i = enemies.begin(); i < enemies.end(); i++) {
                if (i->ID == enemy.ID) {
                    enemies.erase(i);
                    break;
                }
            }
            killedEnemies = killedEnemies + 1;
            
//Problem with this loop below
            for (auto j = bullets.begin(); j < bullets.end(); j++) {   
                if (j->ID == this->ID) {
                    bullets.erase(j);
                    break;
                }
            }
        }
    }
Dawid DXR
  • 1
  • 2
  • It's a double-loop on enemies; the inner loop has a `break;` but the outer loop is in the weeds after the `erase`. – Eljay Jun 06 '22 at 17:24
  • 1
    Related: [Removing item from vector, while in C++11 range 'for' loop?](https://stackoverflow.com/questions/10360461/removing-item-from-vector-while-in-c11-range-for-loop) – Drew Dormann Jun 06 '22 at 17:29
  • it is also likely that `this` is dangling after `bullets.erase(j);`. Unless `Bullet::hit` is a static function. – Drew Dormann Jun 06 '22 at 17:37
  • this->ID is using int ID which is in every Bullet object, maybe I will make separate function only for bullet collision, but this will be less efficient because it will be an additional for loop that will check the same condition, and here I do it by the way removing Enemy – Dawid DXR Jun 06 '22 at 18:02

0 Answers0