分析:

主场景中只需把任意数目的游戏层添加进来就好了

设置点击事件监听,点击后调用jump()方法

设置物理碰撞监听,碰撞后重新开始HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__

#define __HELLOWORLD_SCENE_H__

#include “cocos2d.h”

#include “GameLayer.h”

class HelloWorld : public cocos2d:ayerColor

{

public:

static cocos2d::Scene* createScene();

virtual bool init();

CREATE_FUNC(HelloWorld);

void menuCloseCallback(cocos2d::Ref* pSender);

//把所有游戏层用向量存起来,以便管理

Vector<GameLayer*> games;

};

#endif // __HELLOWORLD_SCENE_H__

HelloWorldScene.cpp

#include “HelloWorldScene.h”

USING_NS_CC;

Scene* HelloWorld::createScene()

{

//创建物理场景

auto scene = Scene::createWithPhysics();

scene->getPhysicsWorld()->setGravity(Point(0,-1000));

scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld:EBUGDRAW_ALL);

auto layer = HelloWorld::create();

scene->addChild(layer);

return scene;

}

bool HelloWorld::init()

{

if ( !LayerColor::initWithColor(Color4B(255,140,0,255)))

{

return false;

}

srand(time(NULL));

Size visibleSize = Director::getInstance()->getVisibleSize();

Point origin = Director::getInstance()->getVisibleOrigin();

//添加游戏层,每层设置不同高度

auto game = GameLayer::create(30);

games.pushBack(game);

addChild(game);

auto game2 = GameLayer::create(200);

games.pushBack(game2);

addChild(game2);

//设置点击监听事件

auto listener = EventListenerTouchOneByOne::create();

listener->onTouchBegan = [this](Touch *t,Event *e)

{

for (auto it = games.begin(); it != games.end(); it++)

{

if((*it)->getEdge()->getBoundingBox().containsPoint(t->getLocation()))

{

(*it)->jump();

}

}

return true;

};

Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);

//设置物理碰撞监听事件

auto contactListener = EventListenerPhysicsContact::create();

contactListener->onContactBegin = [this](PhysicsContact &contact)

{

for (auto i = games.begin(); i != games.end(); i++)

{

(*i)->unscheduleUpdate();

}

Director::getInstance()->replaceScene(HelloWorld::createScene());

return true;

};

Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener,this);

return true;

}

void HelloWorld::menuCloseCallback(Ref* pSender)

{

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)

MessageBox(“You pressed the close button. Windows Store Apps do not implement a close button.”,”Alert”);

return;

#endif

Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

exit(0);

#endif

}