如何在cocos2d-x添加最上层layer也就是顶层。对于最上层的理解就是是指不会因为scene的切换而切换掉的层!那么现在我们就来学习一下怎样给cocos2d-x添加最上层layer

在director的头文件里添加CCLayer *m_pTopLayer;和

  1. ////   set the topLayer
  2. void setTopLayer(CCLayer *layer);

在.cpp里加上以下代码

  1. voidCCDirector::setTopLayer(CCLayer *layer)
  2. {
  3. m_pTopLayer = layer;
  4. }

上面的只是设置layer,如果我们要让其显示在设备上,我们还需要添加以下代码,在drawScene(void)方法里加入以下代码

  1. // draw the top layer
  2. if (m_pTopLayer) {
  3. m_pTopLayer->visit();
  4. }
这样了我们的director已经改完了!

之后我们就写TopLayer了

  1. WindyTopLayer.h:
  2. #ifndef __HeroLegend__WindyTopLayer__
  3. #define __HeroLegend__WindyTopLayer__
  4. #include "cocos2d.h"
  5. class WindyTopLayer : publiccocos2d::CCLayer
  6. {
  7. /// @{
  8. /// @name constructors
  9. public:
  10. CREATE_FUNC(WindyTopLayer);
  11. WindyTopLayer();
  12. virtual ~WindyTopLayer();
  13. staticWindyTopLayer *getInstace();
  14. /// @} end constructors
  15. /// @{
  16. /// @name methods
  17. public:
  18. bool init();
  19. void addNode(cocos2d::CCNode* node);
  20. void showUI();
  21. void removeUI();
  22. /// @} end methods
  23. };
  24. #endif /* defined(__HeroLegend__WindyTopLayer__) */
  25. WindyTopLayer.cpp:
  26. #include "WindyTopLayer.h"
  27. USING_NS_CC;
  28. staticWindyTopLayer* m_topLayer = NULL;
  29. WindyTopLayer::WindyTopLayer()
  30. {
  31. }
  32. WindyTopLayer::~WindyTopLayer()
  33. {
  34. }
  35. WindyTopLayer *WindyTopLayer::getInstace()
  36. {
  37. if (m_topLayer == NULL) {
  38. m_topLayer = WindyTopLayer::create();
  39. m_topLayer->retain();
  40. }
  41. returnm_topLayer;
  42. }
  43. boolWindyTopLayer::init()
  44. {
  45. if (!CCLayer::init()) {
  46. returnfalse;
  47. }
  48. returntrue;
  49. }
  50. voidWindyTopLayer::addNode(cocos2d::CCNode* node)
  51. {
  52. addChild(node);
  53. showUI();
  54. }
  55. voidWindyTopLayer::showUI()
  56. {
  57. if (m_topLayer) {
  58. m_topLayer->onEnter();
  59. CCDirector::sharedDirector()->setTopLayer(m_topLayer);
  60. }
  61. }
  62. voidWindyTopLayer::removeUI()
  63. {
  64. m_topLayer->removeAllChildren();
  65. m_topLayer->onExit();
  66. CCDirector::sharedDirector()->setTopLayer(NULL);
  67. m_topLayer->removeFromParent();
  68. }
逻辑的话,相信大家都能看得懂,都是些基本东西!