C + + learning course, QT aircraft battle course (including detailed steps)

1 project introduction

Airplane battle is a little game that we all know well. This tutorial is to teach you how to make your own airplane battle

First let's take a look at the renderings

The player controls a small plane, and then automatically launches the bullet. If the bullet hits the flying enemy plane, it will shoot the enemy plane and have the effect of explosion

Next, we will explain the requirements of the case, that is, what we need to achieve

  • Scrolling background map
  • Aircraft production and control
  • Production and shooting of bullets
  • Production of enemy aircraft
  • collision detection
  • Explosion effect
  • Sound effect addition

2 create project

The steps to create a project are as follows:

  • Open Qt
  • Follow the wizard to create a project
  • ‚Äč

Base class select QWidget empty window

The first scene is the main scene

Without UI interface

2.1 open Qt

Find the Qt Creator you installed and open it

If you did not choose to set up a shortcut on the desktop during installation, your Qt software location is as follows

C:\qt\Qt5.x.x\Tools\QtCreator\bin

Under this path, find qtcreator.exe and double-click to open it

2.2 follow the wizard to create a project

2.2.1 new project

Click file - > new file or project in the menu or click New Project on the homepage

2.2.2 select template

Select application - > QT widget application for template

2.2.3 project name and location

Give a name to the project and where to save the selected project

After selecting this step, click Next directly in the kit build kit

Type 2.2.4 information

Base class select QWidget

The class name is the name of our first window scene. Here I call it "MainScene" to represent the main scene in the game

Cancel creating content in the interface

2.2.5 complete creation

Click finish in the summary page, and we will start the first step of the project!

3 setting up the main scene

The main scene setting steps are as follows:

  • Add configuration file and save all configuration data in the game
  • Initialize the main scene window size and title

3.1 profile addition

Create a new header file for config.h to record all configuration data in the program for later modification

Add configuration information of window width and height, and set according to the size of background image

/**********Game configuration data**********/
#Define game? Width 512 / / width
 #Define game? Height 768 / / height
 #Define game? Title "aircraft war v1.0" / / Title

3.2 basic settings of main scene

Add a new member function initScene in mainScene.h to initialize the game scene

void  initScene();

Implement the following code in mainScene.cpp

void MainScene::initScene()
{
    //Initialize window size
    setFixedSize(GAME_WIDTH,GAME_HEIGHT);

    //Set window title
    setWindowTitle(GAME_TITLE);
}

Call the function initScene in the constructor MainScene.

MainScene::MainScene(QWidget *parent)
    : QWidget(parent)
{
    //Initialize scene
    initScene();
}

The test operation effect is as shown in the figure:

4 resource import

In the main scenario, there is actually another configuration item that is not implemented, that is, the icon resource in the upper left corner of the window

Then we will import the resources in the game and set the game icon

Resource import steps

  • Generate qrc file
  • Create res folder in the same level directory of the project and paste the resources
  • Edit qrc, add prefix and file
  • Using qrc to generate binary rcc
  • Put the rcc file into the debug directory of the same level
  • Register binaries
  • Add Icon resource

4.1 qrc file generation

Right click the item and click add new file

Select QT - > QT resource file

The name of the resource file is as follows: res

Generate res.qrc file

4.2 create res folder

Create a folder res under the same level directory of the project, and paste the prepared resources into it

4.3 edit qrc file

Right click the qrc file and select Open in Editor

Add prefix ''

Add files select all files under res

4.4 generating rcc binaries by QRC

Because the resource is too large, an error will be prompted:

This error is also known as "insufficient heap space for compiler".

Resource file qrc is too large, out of allocated memory range

So we need to make use of binary resources, and to generate binary resources, we need our qrc file just now

Open the terminal with cmd, locate it in the directory of res.qrc, and input the command

rcc -binary .\res.qrc -o plane.rcc

4.5 copying rcc files

Put the generated rcc file into a debug peer directory

4.6 register binaries

Append configuration data in config.h

#Define game? Res? Path ". / plane. RCC" / / RCC file path

Modify the code in main.cpp

#include "mainscene.h"
#include <QApplication>
#include <QResource>
#include "config.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    //Register external binary resource files
    QResource::registerResource(GAME_RES_PATH);

    MainScene w;
    w.show();

    return a.exec();
}

At this time, the qrc file is useless. Just delete it!

The simplest way to delete is to delete code in the. pro project file, which has nothing to do with the project

Delete the following code:
RESOURCES += \
    res.qrc

4.7 add Icon resources

Additional code in config.h

The syntax of virtual resource path is as follows:

": + prefix name + file path"
#define GAME_ICON  ":/res/app.ico"

Add code in initScene function of mainScene.cpp:

//Set icon resources
    setWindowIcon(QIcon( GAME_ICON));  //Header file include < qicon >

Run tests:

5 map scrolling

Steps:

  • Create map files and classes
  • Add member function and member property to implement member function
  • Game call timer
  • Start timer, monitor timer signal to realize game cycle
  • Calculate the coordinates of elements in the game
  • Draw to screen

5.1 creating map files and classes

Right click project, add new file

Select c + + > C + + class

Change the class name to map, and click Next until the creation is completed

At this point, the files and classes of Map map are created

5.2 member functions and member properties of maps

Add the following code to map.h

#ifndef MAP_H
#define MAP_H
#include <QPixmap>

class Map
{
public:
    //Constructor
    Map();

    //Calculation of map rolling coordinates
    void mapPosition();

public:

    //Map image object
    QPixmap m_map1;
    QPixmap m_map2;

    //Map Y coordinate
    int m_map1_posY;
    int m_map2_posY;

    //Map scrolling range
    int m_scroll_speed;
};

#endif // MAP_H

5.3 implementing member functions

Add new configuration data in config.h

/**********Map configuration data**********/
#Define map path ": / RES / img BG level 1. JPG" / / map image path
 #Define map scroll speed 2 / / map scroll speed

Implementing member functions in map.cpp

#include "map.h"
#include "config.h"

Map::Map()
{
    //Initialize loading map objects
    m_map1.load(MAP_PATH);
    m_map2.load(MAP_PATH);

    //Set the actual y-axis coordinates of the map
    m_map1_posY = -GAME_HEIGHT;
    m_map2_posY = 0;

    //Set map scroll speed
    m_scroll_speed = MAP_SCROLL_SPEED;
}

void Map::mapPosition()
{
    //Process first picture scrolling
    m_map1_posY += MAP_SCROLL_SPEED;
    if(m_map1_posY >= 0)
    {
        m_map1_posY =-GAME_HEIGHT;
    }

    //Process second picture scrolling
    m_map2_posY += MAP_SCROLL_SPEED;
    if(m_map2_posY >= GAME_HEIGHT )
    {
        m_map2_posY =0;
    }
}

5.4 timer addition

Add a new timer object in mainScene.h

QTimer m_Timer;

Add screen refresh interval in config.h

#Define game? Rate 10 / / refresh interval, frame rate in milliseconds

Append code in initScene of MainScene.cpp

//set timer 
    m_Timer.setInterval(GAME_RATE);

5.5 start timer to realize map scrolling

Add new member functions and member objects in MainScene.h

//Start game to start timer object
    void playGame();
    //Update coordinates
    void updatePosition();
    //Drawing events
    void paintEvent(QPaintEvent *event);

    //Map objects
    Map m_map;

Implementing member function in MainScene.cpp

void MainScene::playGame()
{
    //Start timer
    m_Timer.start();

    //Monitor timer
    connect(&m_Timer,&QTimer::timeout,[=](){
        //Update the coordinates of elements in the game
        updatePosition();
        //Redraw picture
        update();
    });
}

void MainScene::updatePosition()
{
    //Update map coordinates
    m_map.mapPosition();
}

void MainScene::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    //draw a map
    painter.drawPixmap(0,m_map.m_map1_posY , m_map.m_map1);
    painter.drawPixmap(0,m_map.m_map2_posY , m_map.m_map2);
}

Test and run the game to realize map scrolling

6 hero plane

The steps are as follows:

  • Create hero files and classes
  • Add member functions and member properties
  • Implementing member functions
  • Create an aircraft object and display
  • Drag and drop aircraft

6.1 create hero files and classes

Create the HeroPlane class and generate the corresponding file

Just like the steps of creating a map, there is no detailed screenshot here

Two files, HeroPlane.h and HeroPlane.cpp, are generated after creation

6.2 member functions and member properties of aircraft

Add code to HeroPlane.h

class HeroPlane
{
public:
    HeroPlane();

    //Bullet launch
    void shoot();
    //Set aircraft position
    void setPosition(int x, int y);

public:
    //Aircraft resource object
    QPixmap m_Plane;

    //Aircraft coordinates
    int m_X;
    int m_Y;

    //Rectangular frame of aircraft
    QRect m_Rect;
};

6.3 member function implementation

Here the plane has a member function to fire bullets, because we haven't made bullets yet

Therefore, this member function can be written as an empty implementation first

Add aircraft configuration parameters in config.h

/**********  Aircraft configuration data**********/
#define HERO_PATH ":/res/hero2.png"

Member function code in heroPlane.cpp:

#include "heroplane.h"
#include "config.h"

HeroPlane::HeroPlane()
{
    //Initialize loading aircraft image resources
    m_Plane.load(HERO_PATH);

    //Initialize coordinates
    m_X = GAME_WIDTH * 0.5 - m_Plane.width()*0.5;
    m_Y = GAME_HEIGHT - m_Plane.height();

    //Initialize rectangle
    m_Rect.setWidth(m_Plane.width());
    m_Rect.setHeight(m_Plane.height());
    m_Rect.moveTo(m_X,m_Y);

}

void HeroPlane::setPosition(int x, int y)
{
    m_X = x;
    m_Y = y;
    m_Rect.moveTo(m_X,m_Y);
}

void HeroPlane::shoot()
{

}

6.4 create aircraft objects and display

Append new member properties in MainScene.h

//Aircraft object
    HeroPlane m_hero;

Append code in paintEvent of MainScene.cpp

//Rendering Heroes
painter.drawPixmap(m_hero.m_X,m_hero.m_Y,m_hero.m_Plane);

Test aircraft displayed on screen

6.5 towing aircraft

Add mouse movement event in MainScene.h

//Mouse movement events
    void mouseMoveEvent(QMouseEvent *event);

Override mouse move event

void MainScene::mouseMoveEvent(QMouseEvent *event)
{
    int x = event->x() - m_hero.m_Rect.width()*0.5; //Mouse position - half the plane rectangle
    int y = event->y() - m_hero.m_Rect.height()*0.5;

    //boundary detection
    if(x <= 0 )
    {
        x = 0;
    }
    if(x >= GAME_WIDTH - m_hero.m_Rect.width())
    {
        x = GAME_WIDTH - m_hero.m_Rect.width();
    }
    if(y <= 0)
    {
        y = 0;
    }
    if(y >= GAME_HEIGHT - m_hero.m_Rect.height())
    {
        y = GAME_HEIGHT - m_hero.m_Rect.height();
    }
    m_hero.setPosition(x,y);
}

The test plane can be towed

7 bullet making

The production steps are as follows:

  • Create bullet files and classes
  • Add member functions and member properties in bullet class
  • Implementing member functions
  • Test bullets

7.1 creating bullet files and classes

Create the Bullet class and generate the corresponding file

After creation, generate two files: bullet.h and bullet.cpp

7.2 member functions and member properties of bullets

Add code to Bullet.h

#ifndef BULLET_H
#define BULLET_H
#include "config.h"
#include <QPixmap>

class Bullet
{
public:
    Bullet();

    //Update bullet coordinates
    void updatePosition();

public:
    //Bullet resource object
    QPixmap m_Bullet;
    //Bullet coordinates
    int m_X;
    int m_Y;
    //Bullet movement speed
    int m_Speed;
    //Is the bullet idle
    bool m_Free;
    //Rectangular frame of bullet (for collision detection)
    QRect m_Rect;
};

#endif // BULLET_H

7.3 implementation of bullet class member function

Add bullet configuration information in config.h

/**********Bullet configuration data**********/
#Define bullet path ": / RES / bullet 11. PNG" / / bullet image path
 #define BULLET_SPEED 5 / / bullet movement speed

The member function is implemented in bullet.cpp. The code is as follows:

#include "bullet.h"

Bullet::Bullet()
{
    //Load bullet resources
    m_Bullet.load(BULLET_PATH);

    //The initial coordinates of bullet coordinates can be set at will, and will be reset later
    m_X = GAME_WIDTH*0.5 - m_Bullet.width()*0.5;
    m_Y = GAME_HEIGHT;

    //Bullet state
    m_Free = true;

    //Bullet speed
    m_Speed = BULLET_SPEED;

    //Bullet rectangle
    m_Rect.setWidth(m_Bullet.width());
    m_Rect.setHeight(m_Bullet.height());
    m_Rect.moveTo(m_X,m_Y);
}
void Bullet::updatePosition()
{
    //If the bullet is idle, coordinate calculation is not required
    //Player aircraft can control the idle state of bullets to false
    if(m_Free)
    {
        return;
    }

    //The bullet moved up
    m_Y  -= m_Speed;
    m_Rect.moveTo(m_X,m_Y);

    if(m_Y <= -m_Rect.height())
    {
        m_Free = true;
    }
}

7.4 test bullets

The bullet itself should be launched by the aircraft. In the test phase, we should write an auxiliary code to see the effect

After testing, the code can be deleted

Add test code in MainScene.h

//Test bullet code
    Bullet temp_bullet;

Add test code to updatePosition in MainScene.cpp

//Test bullet code
    temp_bullet.m_Free = false;
    temp_bullet.updatePosition();

Add test code to paintEvent in MainScene.cpp

//Test bullet code
    painter.drawPixmap(temp_bullet.m_X,temp_bullet.m_Y,temp_bullet.m_Bullet);

Run the program, and a bullet will be fired from the screen

After the test, the test code can be deleted or commented

8 players fire bullets

The steps for players to make bullets are as follows:

  • Hero plane adds new member properties
  • Implement launch member function
  • Main scene control bullet launch

8.1 add new member attributes to aircraft

Add new configuration data in config.h

#define BULLET_NUM 30 / / the total number of bullets in the magazine
 #Define bullet? Interval 20

The new member attributes in HeroPlane.h are as follows:

//Magazine
    Bullet m_bullets[BULLET_NUM];

    //Launch interval record
    int m_recorder;

8.2 member function supplement

Initializing the occurrence interval record in the constructor HeroPlane

//Initialize launch interval record
    m_recorder = 0;

Previously, we implemented a shop function reserved in the hero aircraft class. The code is as follows:

void HeroPlane::shoot()
{
    //Accumulated time interval recording variable
    m_recorder++;
    //Judge if the recorded number does not reach the launch interval, return directly
    if(m_recorder < BULLET_INTERVAL)
    {
        return;
    }
    //Arrival and launch time processing
    //Reset launch interval record
    m_recorder = 0;

    //Bullet launch
    for(int i = 0 ; i < BULLET_NUM;i++)
    {
        //If it's a free bullet to fire
        if(m_bullets[i].m_Free)
        {
            //Change the idle state of the modified bullet to false
            m_bullets[i].m_Free = false;
            //Set the shot coordinates
            m_bullets[i].m_X = m_X + m_Rect.width()*0.5 - 10;
            m_bullets[i].m_Y = m_Y - 25 ;
            break;
        }
    }
}

8.3 shooting bullets in the main scene

Add the following code to the updatePosition member function of MainScene.cpp

//Bullet launch
    m_hero.shoot();
    //Calculate bullet coordinates
    for(int i = 0 ;i < BULLET_NUM;i++)
    {
        //If the bullet status is not idle, calculate the firing position
        if(!m_hero.m_bullets[i].m_Free)
        {
            m_hero.m_bullets[i].updatePosition();
        }
    }

Add the following code to the paintEvent member function of MainScene.cpp:

//Draw a bullet
    for(int i = 0 ;i < BULLET_NUM;i++)
    {
        //If the bullet status is not idle, calculate the firing position
        if(!m_hero.m_bullets[i].m_Free)
        {
            painter.drawPixmap(m_hero.m_bullets[i].m_X,m_hero.m_bullets[i].m_Y,m_hero.m_bullets[i].m_Bullet);
        }
    }

Test run, players can fire bullets

9 enemy aircraft production

The principle of enemy aircraft production is similar to that of bullet production, and it is also to let the enemy aircraft come out at regular intervals

The production steps are as follows:

  • Create enemy files and classes
  • Add member functions and member properties in enemy aircraft class
  • Implementing member functions
  • Enemy aircraft coming out
  • Testing enemy planes

9.1 creating enemy aircraft files and classes

Create the EnemyPlane class and generate the corresponding files

After creation, generate two files enemyPlane.h and enemyPlane.cpp

9.2 enemy aircraft member functions and member attributes

Add the following code to enemyPlane.h:

#ifndef ENEMYPLANE_H
#define ENEMYPLANE_H
#include <QPixmap>

class EnemyPlane
{
public:
    EnemyPlane();

    //Update coordinates
    void updatePosition();
public:
    //Enemy aircraft resource object
    QPixmap m_enemy;

    //position
    int m_X;
    int m_Y;

    //Rectangular frame of enemy aircraft (collision detection)
    QRect m_Rect;

    //state
    bool m_Free;

    //speed
    int m_Speed;
};

#endif // ENEMYPLANE_H

9.3 realization of enemy aircraft member function

Add enemy aircraft configuration information in config.h

/**********Enemy aircraft configuration data**********/
#Define enemy path ": / RES / img plane 5. PNG" / / enemy resource image
 #Define enemy? Speed 5 / / enemy's movement speed
 #Define enemy? Num 20 / / total number of enemy aircraft
 #Define enemy? Interval 30

Implement the member function in enemyPlane.cpp. The code is as follows:

EnemyPlane::EnemyPlane()
{
    //Enemy aircraft resource loading
    m_enemy.load(ENEMY_PATH);

    //Enemy position
    m_X = 0;
    m_Y = 0;

    //Enemy aircraft condition
    m_Free = true;

    //Speed of enemy aircraft
    m_Speed = ENEMY_SPEED;

    //Enemy aircraft rectangle
    m_Rect.setWidth(m_enemy.width());
    m_Rect.setHeight(m_enemy.height());
    m_Rect.moveTo(m_X,m_Y);
}

void EnemyPlane::updatePosition()
{
    //Idle state, do not calculate coordinates
    if(m_Free)
    {
        return;
    }

    m_Y += m_Speed;
    m_Rect.moveTo(m_X,m_Y);

    if(m_Y >= GAME_HEIGHT + m_Rect.height())
    {
        m_Free = true;
    }
}

9.4 enemy aircraft exit

Add the member function of enemy aircraft exit in MainScene.h

Appending the member properties of the enemy aircraft array and the enemy aircraft exit interval record in MainScene.h

//Enemy aircraft coming out
    void enemyToScene();    

    //Enemy aircraft array
    EnemyPlane m_enemys[ENEMY_NUM];

    //Enemy aircraft exit interval record
    int m_recorder;

Initialize interval record attribute, append in initScene member function of MainScene.cpp

m_recorder = 0;

Implement member function enemyToScene

void MainScene::enemyToScene()
{
    m_recorder++;
    if(m_recorder < ENEMY_INTERVAL)
    {
        return;
    }

    m_recorder = 0;

    for(int i = 0 ; i< ENEMY_NUM;i++)
    {
        if(m_enemys[i].m_Free)
        {
            //Enemy aircraft idle state changed to false
            m_enemys[i].m_Free = false;
            //Set coordinates
            m_enemys[i].m_X = rand() % (GAME_WIDTH - m_enemys[i].m_Rect.width());
            m_enemys[i].m_Y = -m_enemys[i].m_Rect.height();
            break;
        }
    }
}

When the timeout signal of PlayGame member function is sent, nemytoscene is added to the slot function first

//Enemy aircraft coming out
        enemyToScene();

Update the enemy aircraft coordinates, and append the code in the updatePosition member function

//Calculation of enemy aircraft coordinates
    for(int i = 0 ; i< ENEMY_NUM;i++)
    {
        //Update coordinates of non idle enemy aircraft
       if(m_enemys[i].m_Free == false)
       {
          m_enemys[i].updatePosition();
       }
    }

Draw enemy aircraft, and add enemy aircraft code to the paintEvent member function

//Enemy aircraft plotting
    for(int i = 0 ; i< ENEMY_NUM;i++)
    {
        if(m_enemys[i].m_Free == false)
        {
            painter.drawPixmap(m_enemys[i].m_X,m_enemys[i].m_Y,m_enemys[i].m_enemy);
        }
    }

Add random number seed

Add random number seed to initScene member function in MainScene.cpp

//Random number seed
    srand((unsigned int)time(NULL));  //Header file include < CTime >

Running and testing the effect of enemy aircraft coming out of the field

10 collision detection

The steps of collision detection are as follows:

  • Add and implement collision detection member functions
  • Call and test functions

10.1 add and implement collision detection function

Add a new member function to MainScene.h

void collisionDetection();

Implement the member function in MainScene.cpp

void MainScene::collisionDetection()
{
    //Traverse all non idle enemy aircraft
    for(int i = 0 ;i < ENEMY_NUM;i++)
    {
        if(m_enemys[i].m_Free)
        {
            //Idle aircraft jumps to next cycle
            continue;
        }

        //Traverse all non idle bullets
        for(int j = 0 ; j < BULLET_NUM;j++)
        {
            if(m_hero.m_bullets[j].m_Free)
            {
                //Idle bullets jump to next cycle
                continue;
            }

            //If the bullet rectangle and the enemy plane rectangle intersect and collide, they will become idle at the same time
            if(m_enemys[i].m_Rect.intersects(m_hero.m_bullets[j].m_Rect))
            {
                m_enemys[i].m_Free = true;
                m_hero.m_bullets[j].m_Free = true;
            }
        }
    }
}

10.2 calling and testing functions

In the playGame member function of MainScene.cpp, append the collision detection code

Run to check the effect. The bullets will disappear when they collide with the enemy aircraft

11 explosion effect

The steps to realize the explosion effect function are as follows:

  • Create explosion files and classes
  • Add member functions and member properties in explosion class
  • Implementing member functions
  • Call and test the effect

11.1 creating explosion files and classes

Create the Bob class and generate the corresponding file

After the creation, two files, Bob. H and Bob. CPP, are generated

11.2 exploded member functions and member properties

Add explosion configuration data to config.h

#Define bomb path ": / RES / bomb -% 1. PNG" / / bomb resource image
 #Define bomb_num 20 / / number of explosions
 #Define BOMB MAX 7 / / maximum index of exploded pictures
 #Define bomb? Interval 20 / / time interval of explosive plot

Add the following code to Bob. H:

#ifndef BOMB_H
#define BOMB_H
#include "config.h"
#include <QPixmap>
#include <QVector>

class Bomb
{
public:
    Bomb();

    //Update information (playback picture subscript, playback interval)
    void updateInfo();

public:

    //Explosion resource array
    QVector<QPixmap> m_pixArr;

    //Location of explosion
    int m_X;
    int m_Y;

    //Explosion state
    bool m_Free;

    //Time interval of explosive plot
    int m_Recoder;

    //Image subscript loaded on Explosion
    int m_index;
};

#endif // BOMB_H

11.3 implementing member functions

Bomb::Bomb()
{
    //Initialize explosion picture array
    for(int i = 1 ;i <= BOMB_MAX ;i++)
    {
        //String splicing, similar to ": / RES / bob-1. PNG"
        QString str = QString(BOMB_PATH).arg(i);
         m_pixArr.push_back(QPixmap(str));
    }

    //Initialize coordinates
    m_X = 0;
    m_Y = 0;

    //Initialize idle state
    m_Free = true;

    //Currently playing picture subscript
    m_index = 0;

    //Explosion interval record
    m_Recoder = 0;
}

void Bomb::updateInfo()
{
    //Idle state
    if(m_Free)
    {
        return;
    }

    m_Recoder++;
    if(m_Recoder < BOMB_INTERVAL)
    {
        //Record that the explosion interval is not reached. return directly. No need to cut the map
        return;
    }
    //Reset record
    m_Recoder = 0;

    //Toggle explosion picture
    m_index++;
    //Note: the subscript in the array starts from 0 and the maximum is 6
    //Reset to 0 if the calculated subscript is greater than 6
    if(m_index > BOMB_MAX-1)
    {
        m_index = 0;
        m_Free = true;
    }
}

11.4 add explosion array

Add explosion array member attribute to MainScene.h

//Explosive array
    Bomb m_bombs[BOMB_NUM];

In the collision detection member function, when collision occurs, set the information of explosion object

//Play blast
                for(int k = 0 ; k < BOMB_NUM;k++)
                {
                    if(m_bombs[k].m_Free)
                    {
                        //Explosion state set to non idle
                        m_bombs[k].m_Free = false;
                        //Update coordinates

                        m_bombs[k].m_X = m_enemys[i].m_X;
                        m_bombs[k].m_Y = m_enemys[i].m_Y;
                        break;
                    }
                }

Append code in updatePosition of MainScene.cpp

//Calculate the pictures played by the explosion
    for(int i = 0 ; i < BOMB_NUM;i++)
    {
        if(m_bombs[i].m_Free == false)
        {
           m_bombs[i].updateInfo();
        }
    }

Append drawing explosion code in paintEvent of MainScene.cpp

//Draw explosion picture
    for(int i = 0 ; i < BOMB_NUM;i++)
    {
        if(m_bombs[i].m_Free == false)
        {
           painter.drawPixmap(m_bombs[i].m_X,m_bombs[i].m_Y,m_bombs[i].m_pixArr[m_bombs[i].m_index]);
        }
    }

Test to achieve explosive effect

12 sound effect adding

The steps of adding sound effect are as follows:

  • Add multimedia module
  • Play sound effects

12.1 add multimedia module

Modify the code in the project file planeWar.pro

QT  += core gui multimedia

12.2 playing sound effect

Add the configuration path of sound effect in config.h

#define SOUND_BACKGROUND ":/res/bg.wav"
#define SOUND_BOMB ":/res/bomb.wav"
Note: qsround should include the header file when it is used\

Add background music to PlayGame

//Start background music
    QSound::play(SOUND_BACKGROUND);

Add explosion sound effect during explosion

//Play sound effects
    QSound::play(SOUND_BOMB);

Test sound effects

13 package and release

  1. Make sure the environment variable is configured with PATH: C:\Qt\Qt5.x.x.x.x\mingw53_32\bin
  2. In QT, switch the running mode to release mode and compile. There will be a release version directory in the outer directory
  3. Copy the rcc binary resource file and executable file (. exe) in the directory to a separate folder
  4. Enter the cmd command mode and switch to the directory where the executable program is located. Execute the following command to copy the library files required by the executable program to the current directory:
    c windeployqt PlaneWar.exe
  5. In addition, the ico icon can also be copied to the directory where the current executable program is located
  6. Start HM NIS EDIT software, select File - > new script wizard in the software, and then follow the wizard
  7. In order to make the installation package installation software also have shortcut icon, in the generated script. Make changes:
    c CreateShortCut "$DESKTOP \ aircraft war. lnk" "$INSTDIR\PlaneWar.exe" CreateShortCut "$DESKTOP \ aircraft war. lnk" "$INSTDIR\PlaneWar.exe" "" "$INSTDIR\app.ico
  8. Click NSIS in the menu bar, and then select compile to generate the installation package on the desktop
640 original articles published, 1190 praised, 1.6 million visitors+
His message board follow

Tags: Qt Qt5 Attribute

Posted on Mon, 10 Feb 2020 01:28:52 -0800 by doctor_james