如何在cocos2d-x添加最上层layer也就是顶层。对于最上层的理解就是是指不会因为scene的切换而切换掉的层!那么现在我们就来学习一下怎样给cocos2d-x添加最上层layer。
在director的头文件里添加CCLayer *m_pTopLayer;和
- //// set the topLayer
- void setTopLayer(CCLayer *layer);
在.cpp里加上以下代码
- voidCCDirector::setTopLayer(CCLayer *layer)
- {
- m_pTopLayer = layer;
- }
上面的只是设置layer,如果我们要让其显示在设备上,我们还需要添加以下代码,在drawScene(void)方法里加入以下代码
- // draw the top layer
- if (m_pTopLayer) {
- m_pTopLayer->visit();
- }
之后我们就写TopLayer了
- WindyTopLayer.h:
- #ifndef __HeroLegend__WindyTopLayer__
- #define __HeroLegend__WindyTopLayer__
- #include "cocos2d.h"
- class WindyTopLayer : publiccocos2d::CCLayer
- {
- /// @{
- /// @name constructors
- public:
- CREATE_FUNC(WindyTopLayer);
- WindyTopLayer();
- virtual ~WindyTopLayer();
- staticWindyTopLayer *getInstace();
- /// @} end constructors
- /// @{
- /// @name methods
- public:
- bool init();
- void addNode(cocos2d::CCNode* node);
- void showUI();
- void removeUI();
- /// @} end methods
- };
- #endif /* defined(__HeroLegend__WindyTopLayer__) */
- WindyTopLayer.cpp:
- #include "WindyTopLayer.h"
- USING_NS_CC;
- staticWindyTopLayer* m_topLayer = NULL;
- WindyTopLayer::WindyTopLayer()
- {
- }
- WindyTopLayer::~WindyTopLayer()
- {
- }
- WindyTopLayer *WindyTopLayer::getInstace()
- {
- if (m_topLayer == NULL) {
- m_topLayer = WindyTopLayer::create();
- m_topLayer->retain();
- }
- returnm_topLayer;
- }
- boolWindyTopLayer::init()
- {
- if (!CCLayer::init()) {
- returnfalse;
- }
- returntrue;
- }
- voidWindyTopLayer::addNode(cocos2d::CCNode* node)
- {
- addChild(node);
- showUI();
- }
- voidWindyTopLayer::showUI()
- {
- if (m_topLayer) {
- m_topLayer->onEnter();
- CCDirector::sharedDirector()->setTopLayer(m_topLayer);
- }
- }
- voidWindyTopLayer::removeUI()
- {
- m_topLayer->removeAllChildren();
- m_topLayer->onExit();
- CCDirector::sharedDirector()->setTopLayer(NULL);
- m_topLayer->removeFromParent();
- }