SFML community forums

Help => Graphics => Topic started by: PapaSmurf on March 23, 2015, 01:38:05 am

Title: Extra sprite spawning when the enemies are redrawn SFML
Post by: PapaSmurf on March 23, 2015, 01:38:05 am
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
Code: [Select]
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?
Title: AW: Extra sprite spawning when the enemies are redrawn SFML
Post by: eXpl0it3r on March 23, 2015, 07:52:46 am
You only erase the sprite if the x position is smaller than -80. Now if one has a bigger x position it won't get removed and your push_back will simply add more elements.
Title: Re: Extra sprite spawning when the enemies are redrawn SFML
Post by: Hiura on March 23, 2015, 09:29:54 am
BTW, there's another flaw in your for loop: when removing one element you should not increase j otherwise you will skip an element.
Title: Re: Extra sprite spawning when the enemies are redrawn SFML
Post by: PapaSmurf on March 23, 2015, 09:41:28 am
Could you advise how to write the loop without skipping the elements?
Title: Re: Extra sprite spawning when the enemies are redrawn SFML
Post by: Hiura on March 23, 2015, 09:43:30 am
In pseudo code:

For (i = 0; i <= size; /*nothing*/)
Do
  if (isCandidateForRemoval(array[i])) remove ith element
  else ++i
End
 
Title: Re: Extra sprite spawning when the enemies are redrawn SFML
Post by: Nexus on March 23, 2015, 09:53:38 am
Never call std::vector::erase() in an iteration loop, it's terribly inefficient. Use std::remove_if() instead.
And iterate with iterators or the range-based for loop, not with indices.

See also:
http://en.sfml-dev.org/forums/index.php?topic=5555.msg36407#msg36407
http://en.sfml-dev.org/forums/index.php?topic=10557.msg73133#msg73133