I have been learning C++ for almost 1 year because i have the crazy idea of making a videogame (simple and classic, no CODs or GTAs on my mind ;)).
I have been watching some great on-line videotutorials and i have started to code a basic shooter but i have a problem with a crashing due to a segmentation fault. I know that kind of problems are derived from a pointer which is called again after being deleted but i think is not the case here. I have been trying to fix it for days but i do not find a solution. Could somebody take a look at it please ?. Here is the code for collision detection in the MAIN function:
And here are the functions to check for collisions in the PROYECTIL (bullet) class:
[code]bool PROYECTIL::colision(std::list<PROYECTIL* >::iterator iteradorPROYECTILES, std::list<ENEMIGO2* >::iterator iteradorEnemigos)
{
// Comprobar colisión con enemigos
if(((*iteradorPROYECTILES)->GetX() > (*iteradorEnemigos)->GetX() + (*iteradorEnemigos)->GetboundX()
|| (*iteradorPROYECTILES)->GetY() > (*iteradorEnemigos)->GetY() + (*iteradorEnemigos)->GetboundY()
|| (*iteradorEnemigos)->GetX() > (*iteradorPROYECTILES)->GetX() + (*iteradorPROYECTILES)->GetboundX()
|| (*iteradorEnemigos)->GetY() > (*iteradorPROYECTILES)->GetY() + (*iteradorPROYECTILES)->GetboundY()) )
returnfalse;
else
{
(*iteradorPROYECTILES)->SetestaVivo(0);
(*iteradorEnemigos)->SetestaVivo(0);
returntrue;
}
}
bool PROYECTIL::fuera(std::list<PROYECTIL* >::iterator iteradorPROYECTILES, int anchura, int altura)
{
if((*iteradorPROYECTILES)->GetX() <= 0 || (*iteradorPROYECTILES)->GetX() + (*iteradorPROYECTILES)->GetboundX() >= anchura
|| (*iteradorPROYECTILES)->GetY() + (*iteradorPROYECTILES)->GetboundY() >= altura || (*iteradorPROYECTILES)->GetY() <= 0)
{
(*iteradorPROYECTILES)->SetestaVivo(0);
returntrue;
}
else
{
((*iteradorPROYECTILES)->SetestaVivo(1));
returnfalse;
}
}
[/code]
Basically i check if the enemy is alive (is inside the screen and not hit by a bullet) and if it is, i check for a collision and if there is a collision i delete it. If not i check if it is outside the screen and if that is the case i delete it. But when the second bullet (usually is the second, but sometimes could be the third or fourth) hits the enemy it crash. Do you think that logic is not correct? Should i rewrite it from scratch?. And in that case could you please give me some advice about how to do it ?.
On line 16 of the first code snippet, you have no guarantee that the iterator returned from erase will not be the end iterator, but if the inner loop continues, you will treat it as if it is not.
Modifying the loop condition on line 9 should alleviate that particular problem.