2.背景类和飞机类的封装
上一章我们说了飞机大战游戏的菜单界面
从这章开始我们就会详细讲解游戏界面,因为所有的游戏逻辑都在游戏界面中。
首先,游戏界面应该有背景,按照我们以前的习惯,直接就在GameScene.cpp中的init()里面创建一个背景了。
这次就不这样做,将这个背景拿出来,单独作为一个类,将它封装起来,这样的好处当你想修改背景的时候,直接
找到这个类,在类里面修改即可。前一种方式,若你GameScene中内容太多,写了几千行代码,你想找都得找半天
o(╯□╰)o
接下来就来实现这个背景的封装
Background.h
class BackGround:public Node
{
public:
int bgy;
CREATE_FUNC(BackGround);
bool init();
void logic(float t);
};
Background.cpp
#include "BackGround.h"
//背景
bool BackGround::init(){
if (!Node::init()) {
return false;
}
this->bgy=0;
auto sp=Sprite::create("background4.png");
this->addChild(sp);
sp->setAnchorPoint(Vec2(0,0));
sp->setTag(10);
auto sp2=Sprite::create("background4.png");
this->addChild(sp2);
sp2->setAnchorPoint(Vec2(0,0));
sp2->setPositionY(sp->getPositionY()+680);
sp2->setTag(11);
this->setAnchorPoint(Vec2(0, 0));
//背景滚动
this->schedule(schedule_selector(BackGround::logic), 0.016);
return true;
}
void BackGround::logic(float t){
auto sp= this->getChildByTag(10);
sp->setPositionY(sp->getPositionY()-1);
if (sp->getPositionY()<=-680) {
sp->setPositionY(0);
}
auto sp2= this->getChildByTag(11);
sp2->setPositionY(sp->getPositionY()+680);
}
ok,这样就完了,里面还加上了背景的滚动。飞机大战嘛,自然飞机是往上飞的,实际呢就只有背景是在往下滚动
而飞机是不动的。以前我也老以为飞机是往上飞的,哈哈。
现在背景类封装好了,但是这样它也不会显示,也不会滚动,接下来需要在GameScene中创建一个背景类对象,使用这个类.
首先,引入头文件Background.h
//1绘制背景
BackGround * bg=BackGround::create();
this->addChild(bg);
现在有背景了,接下来就该实现飞机类了,同样的,将它封装起来。
Player.h
class Player:public Node
{
public:
float px,py;//飞机坐标
int type;//类型
CREATE_FUNC(Player);
bool init();
static Player * createNew(float x,float y,int t);
void moveTo(float x,float y);
};
Player.cpp
#include "Player.h"
bool Player::init(){
if (!Node::init()) {
return false;
}
return true;
}
Player * Player::createNew(float x,float y,int t){
Player * newp=Player::create();
switch (t) {
case 1://第一种飞机
{ Vector<SpriteFrame*> allf;
for(int i=0;i<4;i++)
{auto sf=SpriteFrame::create("player.png",
Rect(47*i,0,47,56));
allf.pushBack(sf);
}
auto animation=Animation::createWithSpriteFrames(allf,0.3);
auto animate=Animate::create(animation);
auto sp=Sprite::create();
sp->runAction(RepeatForever::create(animate));
newp->addChild(sp);
}
break;
case 2://第2种飞机
{ Vector<SpriteFrame*> allf;
for(int i=0;i<8;i++)
{auto sf=SpriteFrame::create("player02.png",
Rect(32*i,0,32,44));
allf.pushBack(sf);
}
auto animation=Animation::createWithSpriteFrames(allf,0.3);
auto animate=Animate::create(animation);
auto sp=Sprite::create();
sp->runAction(RepeatForever::create(animate));
newp->addChild(sp);}
break;
}
newp->setPosition(x, y);
newp->px=x;
newp->py=y;
return newp;
}
void Player::moveTo(float x,float y){
this->setPosition(x,y);
this->px=x;
this->py=y;
}
ok,封装好之后,同样的,需要在GameScene中使用它。
①引入头文件Player.h
②创建飞机类对象并将它添加到场景
//2绘制飞机
Player * p=Player::createNew(160, 50, 2);
this->addChild(p);
p->setTag(110);
ok,这样就完成了背景类和飞机类的封装,下一章会讲一讲子弹类和敌机类的封装,其实和这两个封装大同小异,大家可以先
去试一试,很简单的。
未完待续。。。。
———————————9秒学院学习日志