3.子弹类和敌机类的封装
上一章说到了飞机和背景的封装,这次将会讲解一下子弹和敌机的封装
其实子弹、敌机的封装和飞机的封装差不多,但是有那么一点区别,因为飞机只有一个,而敌机和子弹有无数个
ok,先对子弹进行封装吧
在Bullet.h中
class Bullet : public Node
{
public:
static Bullet * createBullet(float x , float y , int type);
bool init();
CREATE_FUNC(Bullet);
void update(float t); //子弹移动
int type;
};
update函数用来移动子弹,子弹要发射嘛
ok,在Bullet.cpp中
#include "Bullet.h"
#include "GameScene.h"
bool Bullet::init()
{
if (!Node::init()) {
return false;
}
return true;
}
Bullet * Bullet::createBullet(float x , float y , int type)
{
Bullet * nowbullet = new Bullet();
nowbullet->type = type;
switch (type) {
case 1:
{
Sprite * newb = Sprite::create("bullet2.png");
nowbullet->addChild(newb);
// nowbullet->allbullet.pushBack(newb);
nowbullet->setPosition(x , y);
}
break;
case 2:
break;
case 3:
break;
default:
break;
}
//子弹移动
nowbullet->scheduleUpdate();
return nowbullet;
}
void Bullet::update(float t) //子弹移动
{
this->setPositionY(this->getPositionY() + 20);
//当子弹移出屏幕就将其移除并从Vector中移除
if (this->getPositionY() > 480) {
Game * nowgame = (Game *)this->getParent();
nowgame->allbullet.eraseObject(this);
this->removeFromParent();
}
}
ok,子弹就封装好了
在GameScene中去创建他
//GameScene.h
Bullet * bullet; //创建子弹对象
//GameScene.cpp
void Game::newBullet(float t) //绘制子弹
{
bullet = Bullet::createBullet(player->getPositionX(), player->getPositionY(), 1);
allbullet.pushBack(bullet);
this->addChild(bullet);
}
//init()中执行定时器
this->schedule(schedule_selector(Game::newBullet) , 0.1);
这样,就有很多颗子弹出来了,当然,我们需要将它添加到一个Vector中,为了方便后面做碰撞检测
//GameScene.h中
Vector<Bullet *> allbullet; //保存子弹的集合
这样,子弹类就搞定了,接下来是敌机类,敌机类和子弹类差不多,就直接上代码了
Enemy.h
class Enemy : public Node
{
public:
static Enemy * createEnemy(float x ,float y , int type);
bool init();
CREATE_FUNC(Enemy);
void update(float t); //敌机移动
int type; //保存敌机的类型
};
Enemy.cpp
bool Enemy::init()
{
if (!Node::init()) {
return false;
}
return true;
}
Enemy * Enemy::createEnemy(float x ,float y , int type)
{
Enemy * nowEnemy = new Enemy();
switch (type) {
case 1:
{
Sprite * newe = Sprite::create("aaa.png");
nowEnemy->setPosition(x , y);
nowEnemy->addChild(newe);
}
break;
case 2:
{
Sprite * newe = Sprite::create("ccc.png");
nowEnemy->setPosition(x , y);
nowEnemy->addChild(newe);
}
break;
default:
break;
}
nowEnemy->type = type;
//敌机移动
nowEnemy->scheduleUpdate();
return nowEnemy;
}
void Enemy::update(float t) //敌机移动
{
this->setPositionY(this->getPositionX() - 20);
if (this->getPositionY() < 0) {
//移除敌机
Game * nowgame = (Game *)this->getParent();
this->removeFromParent();
nowgame->allenemy.eraseObject(this);
}
}
在GameScene中
//GameScene.h
Vector<Enemy *> allenemy; //保存敌机的集合
Enemy * enemy; //创建飞机对象
//GameScene.cpp
void Game::newEnemy(float t) //绘制敌机
{
int y = size.height - 20;
int ey = random(20, y);
enemy = Enemy::createEnemy(500, ey, random(1, 2));
allenemy.pushBack(enemy);
this->addChild(enemy);
}
//init()中
this->schedule(schedule_selector(Game::newEnemy) , 0.1);
ok,这样敌机类和子弹类我们就封装好了,飞机大战的雏形也出来了。
下一篇将会讲讲飞机大战中的核心内容,子弹与敌机的碰撞检测
Ps:最近比较忙,没来得及更新,各位看官见谅啊,后面会慢慢补上
未完待续。。。
——————————9秒学院学习日志