我如何检测来自不同类的QGraphicsItem和QGraphicsPixmapItem图像之间的碰撞

How can I detect collision between QGraphicsItem and QGraphicsPixmapItem image from different classes

本文关键字:QGraphicsItem 同类 QGraphicsPixmapItem 碰撞 之间 图像 何检测 检测      更新时间:2023-10-16

我有QGraphicsEllipse项目作为场景中的子弹。目标是QPixmap图像,我只想让子弹和图像相互作用,而不是目标对目标的碰撞。子弹是在场景类中创建的,QPixmaps是在对话框类中创建的。

我试着为QPixmaps添加一个QList,创建类似于QList QGraphicsItem *,但不认为编译器喜欢。任何建议都将不胜感激。

void Scene::advance()
{
        QList <QGraphicsItem *> itemsToRemove;
        foreach( QGraphicsItem * item, this->items())
        {
            if( !this->sceneRect().intersects(item->boundingRect()))
            {
                // The item is no longer in the scene rect, get ready to delete it
                itemsToRemove.append(item);
            }
        }
        foreach( QGraphicsItem * item, itemsToRemove )
        {
            this->removeItem(item);
            delete(item);
        }
        QGraphicsScene::advance();
}

BoundRect包含在我的MainTarget类

QRectF MainTargets::boundingRect() const
{
    qreal shift = 1;
        return QRectF(-w/2 -shift, - h/2
                      - shift, w + shift, h + shift);
}
QPainterPath MainTargets::shape() const
{
    QPainterPath path;
    path.addRect(boundingRect());
    return path;
}

编辑

class GraphicsCircle : public QGraphicsRectItem
// class for the pellets
{
public:
    GraphicsCircle(qreal dirx, qreal diry)
        : m_Speed(5)
        , m_DirX(dirx)
        , m_DirY(diry)
    {
        setRect(-3.0,-3.0,8.0,8.0);
        setPos(-140, 195);
        QRadialGradient rGrad( 0.0, 0.0, 20.0, 0.0, 0.0);
        rGrad.setColorAt(0.0, QColor(255,255,255));
        rGrad.setColorAt(0.7, QColor(255,255,225));
        rGrad.setColorAt(1.0, QColor(255,0,0,0));
        setBrush(QBrush(rGrad) );
        setPen(QPen(Qt::NoPen));
    }
    virtual ~GraphicsCircle() {}
    void advance(int phase)
    {
        if(phase == 0) return;
        setPos(x()+m_Speed*m_DirX, y()+m_Speed*m_DirY);
    }
private:
    qreal m_Speed;
    qreal m_DirX;
    qreal m_DirY;
};

我把我的QPixmap对象改为QGraphicsPixmapItems。所以回到最初的问题,如何碰撞颗粒,QGraphicsItems,与目标,QGraphicsPixmapItems。我想应该是某种形式的:

if(pellets->collidesWithItem(targets){
     remove(pellets)
     remove(targets)
 }

代替QPixmap,您可以使用QGraphicsPixmapItem并将图像添加到图形场景中。

此外,您正在调用QGraphicsScene矩形与项目的边界矩形相交,这是在其本地坐标空间:-

if( !this->sceneRect().intersects(item->boundingRect()))

因为它们在不同的坐标空间中,你需要在比较

之前将boundingRect转换为场景的坐标空间。
QRectF sceneBoundingRect = item->mapToScene(item->boundingRect);

然后用这个来比较

if( !this->sceneRect().intersects(sceneBoundingRect))