I want to detect all items in collision with a QGraphicsItem
(item), yet the code below crashes, id like to know the reason.
void PlayerDefences::checkCollisions(QGraphicsItem* item)
{
QList<QGraphicsItem*> itemCollidesWithShip = item->collidingItems(); ///Returns a list of all items that collide with this item.
for (int i = 0; i < itemCollidesWithShip.size(); i++) {
if(itemCollidesWithShip[i]==nullptr) continue;
if(dynamic_cast<Bullet*>(itemCollidesWithShip[i])){ //if the colliding item is of type Bullet*
life-=10;
setActualLife();
item->scene()->removeItem(itemCollidesWithShip[i]);
std::vector<Bullet*>* bullets = Level1::getBulletContainer();
bullets->erase(std::remove(bullets->begin(), bullets->end(), itemCollidesWithShip[i]), bullets->end());
delete itemCollidesWithShip[i] ;
}
}
}
The crash goes away, when i add this line below delete:
itemCollidesWithShip.erase(std::remove(itemCollidesWithShip.begin(), itemCollidesWithShip.end(), itemCollidesWithShip[i]), itemCollidesWithShip.end())