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

标签 c++ qt collision-detection game-physics

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

我尝试为类似于 QList QGraphicsItem * 创建的 QPixmaps 添加 QList,但认为编译器不喜欢这样。任何建议,将不胜感激。

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)
 }

最佳答案

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

此外,您在 QGraphicsScene 矩形上调用 intersects 与项目的边界 Rect,它位于其局部坐标空间中:-

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

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

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

然后用这个做对比

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

关于c++ - 如何检测来自不同类的 QGraphicsItem 和 QGraphicsPixmapItem 图像之间的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22649067/

相关文章:

c++ - CUDA 编译和链接

qt - QProcess:exitCode() 似乎没有返回 %errorlevel%

python - Pygame 矩形上的碰撞

javascript - 如何检测由贝塞尔曲线制成的物体与圆之间的碰撞?

C++ 预留内存空间

c++ - 使用 '&'进行迭代时 'auto'符号有什么作用

qt - 对 QTableWidget 的垂直标题进行排序

c++ - UDP 包丢失因包大小而异

c# - 获取列表中的后续元素 C#

c++ - 对于 C++ unordered_map,如果它是新的,我如何添加一个键值对,如果它的键已经存在,我如何将一个函数应用于该值?