(資料圖片僅供參考)
由于最近要寫(xiě)一個(gè)東西,所以跳過(guò)了一些內(nèi)容,學(xué)到了視圖框架和一些簡(jiǎn)單
的碰撞檢測(cè)。
對(duì)于視圖框架,我的理解還是不夠深,等以后做項(xiàng)目深入了解后,我會(huì)回來(lái)更新。
我是寫(xiě)了一個(gè)自己的場(chǎng)景和兩個(gè)圖形項(xiàng)。先看main.cpp的代碼
#include"myscene.h"#include #include#include"playplany.h"int main(int argc, char *argv[]){QApplication a(argc, argv);QGraphicsView view;//創(chuàng)myscene scene;scene.addRect(0,0,800,800);場(chǎng)景的范圍坐標(biāo)view.setScene(&scene);view.show();return a.exec();}
然后是我的圖形項(xiàng),本來(lái)準(zhǔn)備用照片的,最后每找到,不過(guò)原理都是一樣的
#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//它們畫(huà)的位置是基于場(chǎng)景的{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);//這個(gè)函數(shù)就是對(duì)于進(jìn)入這個(gè)范圍的圖形項(xiàng)就算碰撞return path;}
再看下一個(gè)圖形項(xiàng),其實(shí)與這個(gè)差不多
#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()<
最后就是場(chǎng)景的設(shè)置了,看代碼
#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;}}
【領(lǐng) QT開(kāi)發(fā)教程 學(xué)習(xí)資料, 點(diǎn)擊下方鏈接莬費(fèi)領(lǐng)取↓↓ ,先碼住不迷路~】
點(diǎn)擊這里:
標(biāo)簽: