五篇介绍飞机大战实现过程
cocos2d-x 3.2 |飞机大战:背景与滚动
前情提要第一篇:背景与滚动
如下:
新建项目---->类----->BackGround
BackGround.h
#include <stdio.h>
#include "cocos2d.h"
using namespace cocos2d;
class BackGround:public Node
{
public:
CREATE_FUNC(BackGround);
//create方法会调用init
bool init();
void update(float t);
int count;
};
BackGround.cpp
#include "BackGround.h"
#include "cocos2d.h"
using namespace cocos2d;
bool BackGround::init()
{
if (!Node::init()) {
return false;
}
//添加背景图片
auto Gamebk=Sprite::create("xxxx.jpg");
Gamebk->setTag(10);
//设定背景层锚点 坐标 并添加到当前场景
Gamebk->setAnchorPoint(Vec2(0,0));
Gamebk->setPosition(Vec2(0,0));
this->addChild(Gamebk);
//添加滚动背景层 锚点 坐标 添加到当前场景 标签
auto Gamebk1=Sprite::create("xxxx.jpg");
Gamebk1->setAnchorPoint(Vec2(0,0));
Gamebk1->setPosition(Vec2(0,0));
this->addChild(Gamebk1);
Gamebk1->setTag(11);
//计划任务:滚动贴图
this->scheduleUpdate();
//添加云彩图片
auto Clouds=Sprite::create("xxxxx.png");
Clouds->setScale(0.3, 0.3);
this->addChild(Clouds);
Clouds->setTag(13);
Clouds->setAnchorPoint(Vec2::ZERO);
//随机生成云彩位置
int px=rand()%(int)Director::getInstance()->getWinSize().width;
int py=rand()%(int)Clouds->getContentSize().height+Director::getInstance()->getWinSize().height;
//CCLOG("%d %d ",px,py);
Clouds->setPosition(px, py);
count=0;
return true;
}
void BackGround::update(float t)
{
//移动云彩逻辑
count=count+1;
if (count>1)
{
auto Clouds=this->getChildByTag(13);
Clouds->setPositionY(Clouds->getPositionY()-2);
if (Clouds->getPositionY()<-Clouds->getContentSize().height)
{
// Clouds->setPositionY(
// Director::getInstance()->getWinSize().height+Clouds->getContentSize().height);
int px=rand()%(int)Director::getInstance()->getWinSize().width;
int py=rand()%(int)Clouds->getContentSize().height+Director::getInstance()->getWinSize().height;
Clouds->setPosition(px, py);
}
}
//移动背景逻辑
auto Gamebk=this->getChildByTag(10);
auto Gamebk1=this->getChildByTag(11);
Gamebk->setPositionY(Gamebk->getPositionY()-1);
Gamebk1->setPositionY(Gamebk->getPositionY()+Gamebk->getContentSize().height);
if (Gamebk1->getPositionY()<=0)
{
Gamebk->setPositionY(Gamebk1->getPositionY());
}
}
总结:实现了背景、背景滚动、云彩、云彩随机出生+移动。