分析:

创建一个Layer类作为游戏结束场景

把主场景中的碰撞事件改为切换到游戏结束场景

点击Restart切换回主场景重新开始游戏GameOver.h#ifndef __GAMEOVER_H__

#define __GAMEOVER_H__

#include “cocos2d.h”

#include “HelloWorldScene.h”

USING_NS_CC;

//头文件必须写上,ifndef,不然会导致出错

//比如xxx定义被否决

class GameOver : public LayerColor

{

public:

static Scene* createScene();

virtual bool init();

CREATE_FUNC(GameOver);

private:

LabelTTF *title;

};

#endif

GameOver.cpp

#include “GameOver.h”

Scene* GameOver::createScene()

{

auto GameOverScene = Scene::create();

auto GameOverLayer = GameOver::create();

GameOverScene->addChild(GameOverLayer);

return GameOverScene;

}

bool GameOver::init()

{

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

{

return false;

}

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

title = LabelTTF::create();

title->setString(“Game Over!”);

title->setFontSize(60);

title->setPosition(visibelSize.width/2,visibelSize.height-100);

addChild(title);

auto restart = LabelTTF::create();

restart->setString(“Restart!”);

restart->setFontSize(80);

restart->setPosition(visibelSize.width/2,visibelSize.height/2);

addChild(restart);

auto listener = EventListenerTouchOneByOne::create();

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

{

if(restart->getBoundingBox().containsPoint(restart->convertToNodeSpace(t->getLocation())))

{

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

}

return false;

};

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

return true;

}

效果