如果pixmaps的边缘是透明的,如何检测两个QGraphicsPixmapItems之间的碰撞?

时间:2018-04-12 18:42:42

标签: c++ qt qt5 collision qpixmap

我有两个QGraphicsPixmapItem,两者的边缘都是透明的,并且它们不是矩形的。当我尝试使用QGraphicsItem::collidingItems()时,它只会检查它们的边界是否发生碰撞。有没有办法只检测不透明部分的碰撞?

1 个答案:

答案 0 :(得分:0)

您必须将形状模式设置为QGraphicsPixmapItem::HeuristicMaskShape

  

<强> QGraphicsPixmapItem :: HeuristicMaskShape

     

通过调用QPixmap :: createHeuristicMask()来确定形状。该   性能和内存消耗类似于MaskShape

your_item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);

示例:

<强>的main.cpp

#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>

#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsView w;
    QGraphicsScene *scene = new QGraphicsScene;
    w.setScene(scene);

    QList<QGraphicsPixmapItem *> items;

    for(const QString & filename: {":/character.png", ":/owl.png"}){
        QGraphicsPixmapItem *item = scene->addPixmap(QPixmap(filename));
        item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
        item->setFlag(QGraphicsItem::ItemIsMovable, true);
        item->setFlag(QGraphicsItem::ItemIsSelectable, true);
        items<<item;
    }

    items[1]->setPos(50, 22);
    if(items[0]->collidingItems().isEmpty())
        qDebug()<<"there is no intersection";
    w.show();
    return a.exec();
}

enter image description here

输出:

there is no intersection

完整示例可在以下link

中找到