I try to program a top-down-shooter in SFML at the moment, but ran into a problem. I’m quite new to C++ and programming in general, so please excuse messy code and/or overly complicated solutions.
I have two std::lists, one containing the randomly spawning enemies, the other containing the bullets I fired. When a bullet hits a enemy, both of them should get erased, but it doesn’t work.
Here’s the problem-part of my code:
for(MonsterIt = MonsterList.begin(); MonsterIt != MonsterList.end(); MonsterIt++)
{
//Here would be Monster-Movement
//Collision Monster-Player (MonsterIt = iterator of MonsterList)
if ((MonsterIt -> getPosition().x + 25) >= PlayerX - 25 &&
(MonsterIt -> getPosition().x - 25) <= PlayerX + 25 &&
(MonsterIt -> getPosition().y + 25) >= PlayerY - 25 &&
(MonsterIt -> getPosition().y - 25) <= PlayerY + 25 )
{
MonsterList.erase(MonsterIt);
break;
}
window.draw(*MonsterIt);
}
That’s the way I’ve done collision between Monster and Player. That worked fine, so I tried the same with Monsters and Lasers:
for(LaserIt = LaserList.begin(); LaserIt != LaserList.end(); LaserIt++)
{
//Here would be "Laser-Movement"
//Collision-Laser // Doesn't work
if ((MonsterIt -> getPosition().x + 25) >= //
(LaserIt -> getPosition().x - 7) && //
(MonsterIt -> getPosition().x - 25) <= //
(LaserIt -> getPosition().x + 7) && //
(MonsterIt -> getPosition().y + 25) >= //
(LaserIt -> getPosition().y - 7) && //
(MonsterIt -> getPosition().y - 25) <= //
(LaserIt -> getPosition().x + 7)) //
{ //
MonsterList.erase(MonsterIt); //
//
LaserList.erase(LaserIt); //
//
break; //
} //
window.draw(*LaserIt);
}
When I put in the part of code I marked (with // on right side) I get a “list iterator not dereferencable”-error while debugging as soon as I shoot. When I cut out said code it runs fine (I can shoot, walk into monsters and they disappear, etc.). Because of that I guess the rest of my code is working.
So, is collision between iterators of different lists even possible?
And if so, how do I do it?
If you need more information or code, please ask. I’d be glad for your help…
The iterator you use is not valid.
There are several solutions to your problems. First one:
This solution is not really C++ish. With OOP, you can have a much clearer code:
Then,
Monsteris a class like the following:class Monster
{
bool alive;
public:
bool isAlive() const { return alive; }