消息!Qt学习之视图框架下的简单的碰撞检测
2023-05-21 10:42:56
来源:QT教程
(资料图片仅供参考)
由于最近要写一个东西,所以跳过了一些内容,学到了视图框架和一些简单
的碰撞检测。
对于视图框架,我的理解还是不够深,等以后做项目深入了解后,我会回来更新。
我是写了一个自己的场景和两个图形项。先看main.cpp的代码
#include"myscene.h"#include #include#include"playplany.h"int main(int argc, char *argv[]){QApplication a(argc, argv);QGraphicsView view;//创myscene scene;scene.addRect(0,0,800,800);场景的范围坐标view.setScene(&scene);view.show();return a.exec();}
然后是我的图形项,本来准备用照片的,最后每找到,不过原理都是一样的
#ifndef ENEMYPLANY_H#define ENEMYPLANY_H#include#include#includeclass enemyplany:public QGraphicsObject{public:enemyplany();QRectFboundingRect() const;void paint(QPainter *painter,const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr);void timerEvent(QTimerEvent *event);QPainterPath shape() const;int x;int y;};#endif // ENEMYPLANY_H#include "enemyplany.h"enemyplany::enemyplany(){startTimer(1000);x=500;y=100;}QRectF enemyplany::boundingRect() const//它们画的位置是基于场景的{return QRectF(0,0,800,800);}void enemyplany::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){painter->drawRect(x,y,40,50);update();}void enemyplany::timerEvent(QTimerEvent *event){x-=30;}QPainterPath enemyplany::shape() const{QPainterPath path;path.addRect(x,y,40,50);//这个函数就是对于进入这个范围的图形项就算碰撞return path;}
再看下一个图形项,其实与这个差不多
#ifndef PLAYPLANY_H#define PLAYPLANY_H#include#include#includeclass playplany:public QGraphicsObject{public:playplany();QRectFboundingRect() const;void paint(QPainter *painter,const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr);void timerEvent(QTimerEvent *event);QPainterPath shape() const;int x=100;int y=100;};#endif // PLAYPLANY_H#include "playplany.h"#includeplayplany::playplany(){startTimer(1000);}QRectF playplany::boundingRect() const{return QRectF(0,0,800,800);}void playplany::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){painter->drawRect(x,y,40,50);update();}void playplany::timerEvent(QTimerEvent *event){qsrand((unsigned)time(NULL));x+=30;}QPainterPath playplany::shape() const{QPainterPath path;path.addRect(x,y,40,50);//qDebug()<
最后就是场景的设置了,看代码
#ifndef MYSCENE_H#define MYSCENE_H#include#include"enemyplany.h"#include"playplany.h"#include#includeclass myscene:public QGraphicsScene{public:myscene();QRectFboundingRect() const;private:enemyplany *enem_plany;playplany *play_plany;void timerEvent(QTimerEvent *e);};#endif // MYSCENE_H#include "myscene.h"myscene::myscene(){enem_plany=new enemyplany;play_plany=new playplany;this->addItem(enem_plany);this->addItem(play_plany);startTimer(50);}QRectF myscene::boundingRect() const{return QRectF(0,0,800,800);}void myscene::timerEvent(QTimerEvent *e)//每50秒判断一次是否碰撞{if(enem_plany->collidesWithItem(play_plany)){play_plany->x-=30;}}
【领 QT开发教程 学习资料, 点击下方链接莬费领取↓↓ ,先码住不迷路~】
点击这里: