0
\$\begingroup\$

I am making a game in sfml and at the moment when all of the enemies die. They are set to respawn however when this is happening they are respawning with one extra sprite than before.

The code for loading in the sprites is

unsigned int orcNumber = 5;
for (int i = 0; i < orcNumber; i++)
{
    SpriteVector.push_back(ogreSprite);
    SpriteVector[i].setPosition(spawnPointX[i], spawnPointY[i]);
}

The code for removing the enemies if they are offscreen or shot is similar to below using erase.

for (unsigned j = 0; j < SpriteVector.size(); j++)
{
    if (this->SpriteVector[j].getPosition().x < 0 - 80 )
    {
        //this succesfully removes the object from the vector
        SpriteVector.erase(SpriteVector.begin() + j); 
        std::cout << "Container size..." << SpriteVector.size() << "\n";
    }
}

The statement for redrawing them is:

unsigned int orcNumberRespawn = 5;
if (SpriteVector.size() <= 1)
{           
    for (int i = 0; i < orcNumberRespawn; i++)
    {
        SpriteVector.push_back(ogreSprite);
        SpriteVector[i].setPosition(spawnPointX[i], spawnPointY[i]);
    }
}

window.draw(SpriteVector[i]);

Can anyone identify why when the sprites need to be redrawn it draws with + 1 sprite everytime?

\$\endgroup\$
1
\$\begingroup\$

You are changing the size of the array inside the loop, but not updating the loop index to match.. Thus you skip one item in the list every time you delete one.

for (unsigned j = 0; j < SpriteVector.size(); j++)
{
    if (this->SpriteVector[j].getPosition().x < 0 - 80 )
    {
        //this succesfully removes the object from the vector
        SpriteVector.erase(SpriteVector.begin() + j); 
        std::cout << "Container size..." << SpriteVector.size() << "\n";

        // Since we removed j, the j'th item gets skipped when you loop (j++)

    }
}

A very simple solution could be to move through the list backwards:

for (size_t j = SpriteVector.size(); j--;)
{
    if (this->SpriteVector[j].getPosition().x < 0 - 80 )
    {
        //this succesfully removes the object from the vector
        SpriteVector.erase(SpriteVector.begin() + j); 
        std::cout << "Container size..." << SpriteVector.size() << "\n";
    }
}

This way, when you change the order of all the items after J, it doesn't matter. A more flexible solution could be to make a 2nd list, a list of items to remove.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.