繁体   English   中英

如何检测来自不同类的QGraphicsItem和QGraphicsPixmapItem图像之间的冲突

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

我有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 rect上与该项目的边界Rect相交的矩形,该矩形位于其局部坐标空间中:-

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

由于它们位于不同的坐标空间中,因此在比较之前,需要将boundingRect转换为场景的坐标空间

QRectF sceneBoundingRect = item->mapToScene(item->boundingRect);

然后使用它进行比较

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM