Qt工作笔记-使用QGraphicsItem加载图片并实现碰撞

因为要做一个游戏,在线只是一个知识点例子,作下笔记而已。只给出伪代码,游戏作玩,开源发布!!!


这里有2个知识点

一个是QGraphicsItem的绘图。

一个是QGraphicsItem的碰撞。


实现绘图要重写:boundingRect()和paint();

一定要保证所有的绘图都要在boundingRect()的边界之中。

本次绘图代码如下:

QRectF Graphic::boundingRect()const{
    qreal penWidth=1;
    return QRectF(0-penWidth/2,0-penWidth/2,
                  100,130);
}
void Graphic::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
    painter->drawImage(QRectF(0,0,100,130),QImage(":/img/plane.png"));
}


图形视图框架提供了图形项之间的碰撞检测,碰撞检测可以使用两种方法来实现:
1.重新实现QPainterPath QGraphicsItem::shape()函数来返回图形项准确的形状,然后使用默认的collidesWithItem()
函数通过两个图形项形状之间的交集来判断是否发生碰撞。如果图形项的形状很复杂,那么进行这个操作是非常耗时

的。

2.如果没有重新实现shape()函数,那么它默认会调用boundingRect()函数返回一个简单的矩形。

这次就用boundingRect进行判断。

伪代码如下:

void Graphic::keyPressEvent(QKeyEvent *event){

    if(event->key()==Qt::Key_Down){
        moveBy(0,10);
    }

    if(event->key()==Qt::Key_Up){
        moveBy(0,-10);
    }

    if(event->key()==Qt::Key_Left){
        moveBy(-10,0);
    }

    if(event->key()==Qt::Key_Right){
        moveBy(10,0);
    }

    QList<QGraphicsItem *> list = collidingItems();
    if(!list.isEmpty()) {
        list.at(0)->hide();
    }
}
其中collidingItems返回与这个之碰撞的所有图像!


猜你喜欢

转载自blog.csdn.net/qq78442761/article/details/80358327