首先,我们在头文件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
函数将draw
与update
方法设置为bulletDraw
与bulletUpdate
。并且,创建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
中。