Question

I'm making a 2D game in c++ and am trying to shoot enemies. When a bullet collides with the first enemy rendered then the enemy is killed fine, and it is removed from the enemys vector. However after the first enemy has been killed, other enemies no longer die.

This is where the check is carried out in the update function.

size = enemys.size();
for (int i = 0; i<size; i++)
    {
        double x = enemys[i].getEnemyX();
        double y = enemys[i].getEnemyY();
        bool isShot = enemyShot(x,y);
        if(isShot == true){
            enemys.erase(enemys.begin()+i);
            size = size - 1;
        }
    }

This is the enemyShot function.

bool GameActivity::enemyShot(double enemyX, double enemyY)
{
int size = bullets.size();
for (int i = 0; i<size; i++)
{
    double x = bullets[i].getX();
    double y = bullets[i].getY();
    if (x >= enemyX-5.0 && x <= enemyX+5.0 && y >= enemyY-5.0 &&  y <= enemyY + 5.0){
        return true;
    }
    else{
        return false;
    }
}
}
Was it helpful?

Solution

The problem is that your vector of enemies is updated after each erasure - thus, the current index is no longer correct. A better way to iterate the enemys vector is to start from the end of the enemys vector. That way, when you erase an element, the index is still correct:

for (size_t i = enemys.end (); i> 0; --i) {
    double x = enemys[i].getEnemyX();
    double y = enemys[i].getEnemyY();
    bool isShot = enemyShot(x,y);
    if(isShot == true){
        enemys.erase(enemys.begin()+i);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top