thatboytitz
thatboytitz

Reputation: 77

QT collision detection with custom QGraphicsItem classes

I'm trying to create a bullet class that deletes an enemy class once it detects it's colliding with something. I'm trying to do something like :

void bullet::DoCollision()
{
    if(collidesWithItem(enemy))
    {
        QList<enemy> collisions = collidingItems(enemy);
    }
    //sudo code
    //foreach collision
    //delete enemy
}
//delete myself

Am I going about this the right way? They are both QGraphicsItems.

Upvotes: 4

Views: 6497

Answers (1)

Nejat
Nejat

Reputation: 32665

You can use QGraphicsItem::collidingItems to return a list of all items that collide with this item. After getting the list, you can detect if the colliding items are of type enemy and remove them if so :

QList<QGraphicsItem *> list = collidingItems() ;

foreach(QGraphicsItem * i , list)
{
    enemy * item= dynamic_cast<enemy *>(i);
    if (item)
    {
        myScene->removeItem(item);
    }
}

Upvotes: 3

Related Questions