其他章节链接

​QT飞机大战一(游戏场景配置)​

​QT飞机大战三(子弹类)​


QT飞机大战二(飞机类)_#include

如图所示

飞机,当然要有自己的坐标位置

有自己的资源图片

另外需要设置自己的矩形框,毕竟后续需要用于和其他子弹,敌机检测是否相撞

需要有发射子弹的函数,那么这个子弹肯定也是一个类,子弹类在下一节

需要提供一个更新飞机位置的函数,因为飞机会随着鼠标拖拽移动

至于随着鼠标移动,我们只需要在主场景中重写​​mouseMoveEvent(QMouseEvent *event)​​时间即可

飞机类 H e r o P l a n e HeroPlane HeroPlane

​heroplane.h​

#ifndef HEROPLANE_H
#define HEROPLANE_H
#include <QPixmap>
#include <QRect>
#include <bullet.h>
class HeroPlane
{
public:
HeroPlane();
//发射子弹函数
void shoot();
//设置飞机的位置函数
void setPosition(int x,int y);

public:
//飞机资源图片
QPixmap m_Plane;
//飞机坐标
int m_x,m_y;
//飞机的矩形边框
QRect m_Rect;
//弹夹
Bullet bullets[BULLET_NUM];
//子弹发射间隔记录,因为定时器10ms一次,但是子弹不能发那么快,用变量控制一下
int bullet_recorder;
};

#endif // HEROPLANE_H

​heroplane.cpp​

#include "heroplane.h"
#include <config.h>

HeroPlane::HeroPlane()
{
//加载飞机图片
m_Plane.load(HERO_PATH);
//初始化飞机坐标
m_x = (GAME_WIDTH-m_Plane.width() )/2;
m_y = GAME_HEIGHT-m_Plane.height();
//初始化矩形边框
m_Rect.setWidth(m_Plane.width());
m_Rect.setHeight(m_Plane.height());
}

void HeroPlane::shoot()
{
//如果记录的数字没有到发射间隔
if( ++bullet_recorder<BULLET_INTERVAL ) return;
bullet_recorder = 0;
//发射子弹,在弹夹里找到空闲的子弹发射
for(int i=0;i<BULLET_NUM;i++)//找到空闲子弹
{
if( !bullets[i].m_Free ) continue;//不是空闲的
bullets[i].m_Free = false;//发射出去
bullets[i].m_x = m_x+( m_Plane.width()-bullets[i].m_Bullet.width() )/2;
bullets[i].m_y = m_y;//子弹发出去,位置和自己一样
break;
}
}

void HeroPlane::setPosition(int x,int y)//设置飞机位置
{
m_x = x, m_y = y;
m_Rect.moveTo(m_x,m_y);
}

然后在​​MainScene​​中捕捉一下鼠标的拖拽

void MainScene::mouseMoveEvent(QMouseEvent *event)
{
int x = event->x()-m_hero.m_Rect.width()/2;
int y = event->y()-m_hero.m_Rect.height()/2;
if( x<0 ) x = 0;
if( y<0 ) y = 0;
if( x>this->width()-m_hero.m_Rect.width() ) x = this->width()-m_hero.m_Rect.width();
if( y>this->height()-m_hero.m_Rect.height() ) y = this->height()-m_hero.m_Rect.height();
m_hero.setPosition(x,y);//设置飞机的坐标
}

那么随着定时器的记录,飞机不断更新坐标,不断调用 p a i n t e r E v e n t painterEvent painterEvent绘制

就可以达到移动的目的.