想让游戏暂停,只要调用 CCDirector::sharedDirector()->pause(); 就行了,反止重新游戏就是 CCDirector::sharedDirector()->resume();
但这有一个问题就是游戏层依然能接受触摸反应,我们想按下pause键游戏暂停,但游戏内容不再接受触摸,该怎么办呢?
pause键一般是CCMenu, 它的触摸优先级为-128 数值越小越优先。所以我们想到的是游戏暂停的时候在游戏GameLayer层上加一个看不见的层,估且叫NoTouchLayer吧,让它屏蔽一切触摸。此类实现如下:
#pragma once #include "cocos2d.h" class NoTouchLayer : public cocos2d::CCLayer { public: virtual bool init(); CREATE_FUNC(NoTouchLayer); virtual void registerWithTouchDispatcher(); virtual bool ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); virtual void ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); virtual void ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); };
#include "NoTouchLayer.h" USING_NS_CC; bool NoTouchLayer::init() { if (!CCLayer::init()) { return false; } setTouchEnabled(true); return true; } void NoTouchLayer::registerWithTouchDispatcher() { //优先级低于-128(CCMenu),同时高于其他层(0),true表示吞噬触摸 这样就屏敝了其他层的触摸 CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, -127, true); CCLayer::registerWithTouchDispatcher(); } bool NoTouchLayer::ccTouchBegan (CCTouch *pTouch, CCEvent *pEvent) { return true; //返回true接受触摸 } void NoTouchLayer::ccTouchMoved (CCTouch *pTouch, CCEvent *pEvent) { } void NoTouchLayer::ccTouchEnded (CCTouch *pTouch, CCEvent *pEvent) { }
游戏暂停时:
CCDirector::sharedDirector()->pause(); //屏蔽一切触摸方应,此屏能够屏蔽一切触摸 noTouchLayer = NoTouchLayer::create(); this->addChild(noTouchLayer);
CCDirector::sharedDirector()->resume(); this->removeChild(noTouchLayer, true);这个noTouchLayer可在GameLayer的头文件中声音为一个成员变量
原文地址:http://blog.csdn.net/qiou2719/article/details/40781591