【cocos2dx 3.2】一个都不能死4 游戏层

分析:

  1. 游戏层包含人,物块,地面三个元素,故定义为Layer类
  2. 往游戏层中加入元素,设置schedule定时添加物块
  3. 添加jump()方法,使人物可以向上跳起
  4. 在主场景中添加游戏层

GameLayer.h

#include "cocos2d.h"
#include "Hero.h"
#include "Block.h"
#include "Edge.h"

class GameLayer : public Layer
{

public:
	//根据Y轴位置初始化游戏层
	virtual bool init(float positionY);
	static GameLayer* create(float positionY);

	//按一定时间间隔添加物块
	void resetTime();
	void addBlock();
	void update(float dt);

	//向上跳
	void jump();

	Node* getEdge();

private:
	float _positionY;
	Hero *_hero;
	Node *_edge;
	int oldTime;
	int curTime;


	Size visibleSize;
};

GamLayer.cpp

#include "GameLayer.h"

USING_NS_CC;

GameLayer* GameLayer::create(float positionY)
{
	auto game = new GameLayer();
	game->init(positionY);
	game->autorelease();
	return game;
}

bool GameLayer::init(float positionY)
{
	Layer::init();

	_positionY = positionY;
	visibleSize = Director::getInstance()->getVisibleSize();

	//重置计时器
	resetTime();

	//添加物理边界
	_edge = Edge::create();
    _edge->setPosition(visibleSize.width/2, _positionY+70);
	addChild(_edge);

	//添加地板
	auto floor = Sprite::create();
	floor->setTextureRect(Rect(0,0,visibleSize.width,3));
	floor->setColor(Color3B(0,0,0));
	floor->setPosition(visibleSize.width/2,_positionY+1.5);
	addChild(floor);

	//添加人物
	_hero = Hero::create();
	_hero->setPosition(50,_positionY+_hero->getContentSize().height/2);
	addChild(_hero);

	//添加障碍物计时器
	scheduleUpdate();

	return true;
}

//按一定时间间隔添加物块
void GameLayer::update(float dt)
{
	oldTime++;

	if(oldTime >= curTime)
	{
		addBlock();
		resetTime();
	}
}

void GameLayer::resetTime()
{
	oldTime = 0;
	curTime = (rand()%60)+100;
}

void GameLayer::addBlock()
{
	auto b = Block::create();
	b->setPositionY(_positionY+b->getContentSize().height/2);
	addChild(b);
}

void GameLayer::jump()
{
	 if (_hero->getPositionY()<_positionY+_hero->getContentSize().height/2+5) {
		 _hero->getPhysicsBody()->setVelocity(Point(0, 400));
    }
}

Node* GameLayer::getEdge()
{
	return _edge;
}




你可能感兴趣的:(【cocos2dx 3.2】一个都不能死4 游戏层)