1

I have a bullet class that I want to delete upon hitting anything but if it hits an enemy, I want it to delete the enemy as well. It was working on my desktop but upon switching to my laptop, it starts crashing whenever it removes. Currently my scene is outside in a different class in Dialog.cpp

here's my code:

bullet.cpp

void bullet::DoCollision()
{
    QList<QGraphicsItem *> list = collidingItems() ;

    foreach(QGraphicsItem * i , list)
    {
        if (i->type() == 3)
        {
            QGraphicsItem * item= i;
            delete item;

            qDebug() << "bye";
        }
    }
    m_FireTimer->stop();

    delete this;
}
thatboytitz
  • 77
  • 2
  • 6
  • Nothing that strikes me as an immediate crash. However: You may want to set things to NULL after deleting them so they don't get accidentally deleted twice (e.g. in the dtor of your class). You could use http://qt-project.org/doc/qt-5/qtalgorithms.html#qDeleteAll-2 to replace the loop. – cellcortex May 08 '14 at 17:22
  • At home I could continue running and display "you win" after all the enemies were killed over on my laptop it immediate crashes once you hit the first enemy. – thatboytitz May 08 '14 at 17:26
  • @cellcortex I'm not entire sure how to edit my last comment. I tried doing that however it didn't work. It still immediately crashes – thatboytitz May 08 '14 at 17:36
  • I suspect your problem is because you use `delete this`. Rather remove this line and let the owner of the bullet do the deleting. – RobbieE May 08 '14 at 18:11
  • @RobbieE It turns out the bullets weren't causing the crash. The Debugger would crash at the enemy destructor – thatboytitz May 08 '14 at 19:19

1 Answers1

0

You should use QGraphicsScene::removeItem(QGraphicsItem * item) which removes the item and all its children from the scene. You should hold a pointer to your scene in a variable like myScene.

Your code should be like:

void bullet::DoCollision()
{
    QList<QGraphicsItem *> list = collidingItems() ;

    foreach(QGraphicsItem * i , list)
    {
        if (i->type() == 3)
        {
            QGraphicsItem * item= i;
            myScene->removeItem(item);
            delete item;

            qDebug() << "bye";
        }
    }
    m_FireTimer->stop();

    delete this;
}
Nejat
  • 31,784
  • 12
  • 106
  • 138