32.飞机大战:子弹与敌机

  • 学习人数 15K+
  • 适合有C语言基础人群学习
avatar
林耿亮

你好编程主讲老师

首先,我们在头文件bullet.h中声明子弹对象。

头文件bullet.h

#pragma once

#include <easyx.h>
#include "sprite.h"

struct bullet {
    struct sprite super;
    IMAGE *imgBullet;
    IMAGE *imgBulletMask;
};

void bulletInit(struct bullet*);
void bulletDestroy(struct bullet*);

子弹对象继承于sprite对象。并且,有一张子弹图片和一张掩码图片。

子弹图片img/bullet/bullet.png

子弹图片

子弹掩码图片img/bullet/bullet_mask.png

子弹掩码图片

接下来,我们再看看源文件bullet.cpp中的内容。

源文件bullet.cpp

#include "bullet.h"
#include "image.h"

void bulletDraw(struct bullet* b)
{
    putTransparentImage(b->super.x, b->super.y, b->imgBulletMask, b->imgBullet);
}

void bulletUpdate(struct bullet* b)
{
    b->super.y -= 8;
}

void bulletInit(struct bullet* b)
{
    b->super.draw = (void (*)(struct sprite*))bulletDraw;
    b->super.update = (void (*)(struct sprite*))bulletUpdate;

    //  members
    b->imgBullet = new IMAGE;
    b->imgBulletMask = new IMAGE;
    loadimage(b->imgBullet, "img/bullet/bullet.png");
    loadimage(b->imgBulletMask, "img/bullet/bullet_mask.png");
}

void bulletDestroy(struct bullet *b)
{
    delete b->imgBullet;
    delete b->imgBulletMask;
}

bulletDraw用于绘制子弹。bulletUpdate用于移动子弹,每次y坐标向上移动8像素。

bulletInit函数将drawupdate方法设置为bulletDrawbulletUpdate。并且,创建IMAGE对象并加载对应图片。

接着,我们需要让子弹出现在场景当中。在mainScene场景中增加数组vecBullets用于存放场景中的子弹。

头文件mainscene.h

#pragma once

#include "scene.h"
#include "background.h"
#include "hero.h"
#include "vector.h"

struct mainScene {
    struct scene super;
    hero* hero;
    background* bk;
    vector vecElements;
    vector vecBullets;   //  子弹数组
};

void mainSceneInit(struct mainScene* s);
void mainSceneDestroy(struct mainScene* s);

在源文件mainscene.cpp中增加generateBullet函数用于在场景中生成子弹。子弹产生后的初始坐标在英雄飞机的头部,也就是英雄飞机的左上角坐标(x,y),x加32,y减6的位置。并且,把子弹追加到子弹数组vecBullets中。

子弹初始位置