I'm working on the collision detection portion of a small game and am stuck on one part. Here is the code with a description (in english) below. Sorry if the code is a bit messy.
Code: Select all
void all_collision(Player*& bluePlayer, Player*& redPlayer)
{
std::vector<Pizza*>::iterator itr;
for(itr = bluePlayer->pizzas.begin(); itr < bluePlayer->pizzas.end(); ++itr)
{
if( collision_check( (*itr)->getrect(), redPlayer->getrect() ) )
{
delete (*itr);
itr = bluePlayer->pizzas.erase(itr);
}
}
for(itr = redPlayer->pizzas.begin(); itr < redPlayer->pizzas.end(); ++itr)
{
if( collision_check( (*itr)->getrect(), bluePlayer->getrect() ) )
{
delete (*itr);
itr = redPlayer->pizzas.erase(itr);
}
}
}
Code: Select all
void Player::throw_pizza()
{
Pizza* temp = new Pizza(pizzaSurface);
temp->collisionBox.x = collisionBox.x;
temp->collisionBox.y = collisionBox.y;
pizzas.push_back(temp);
}
My problem comes when the first function all_collision() goes to delete one of the Pizzas. (This is my very first attempt at dealing with dynamically allocated objects within an array so I'm not sure if the allocation is wrong, the removal, or BOTH ) What happens is the game throws a runtime error as seen below.
The interesting thing I discovered is that this only happens on the last Pizza (pizzas are projectiles in this game) that is deallocated. If I throw 5 pizzas, the first 4 are removed just fine. My only guess so far is that I am perhaps setting the final iterator itr to a null value and that is causing the final iteration of the for loop to shit itself. Any help here would be appreciated.