Cocos2D-x游戏开发之:CCNotificationCenter观察者模式基础

前端之家收集整理的这篇文章主要介绍了Cocos2D-x游戏开发之:CCNotificationCenter观察者模式基础前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Cocos2D-X为我们准备了太多东西,当我们想要监听一个动作但是都不能老是盯在这一件事情上的时候就可以用他为我们量身定制的观察者模式,今天我们初步来学习一下这个传说很久的观察这模式在Cocos2D-X中的简单运用。

其实观察者模式的初步学习还是很简单的我们只要定义两个函数即可:

  1. classHelloWorld:publiccocos2d::CCLayer
  2. {
  3. public:
  4. virtualboolinit();
  5. staticcocos2d::CCScene*scene();
  6. voidsengMsg(CCObject*pSender);
  7. voidtestMSG(CCObject*pSender);
  8. CREATE_FUNC(HelloWorld);
  9. };
  10. #endif//__HELLOWORLD_SCENE_H__

然后在init()函数添加事件的监听。在SendMSG()函数中发送事件消息。
copy
    boolHelloWorld::init()
  1. boolbRet=false;
  2. do
  3. {
  4. //////////////////////////////////////////////////////////////////////////
  5. //superinitfirst
  6. CC_BREAK_IF(!CCLayer::init());
  7. CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(HelloWorld::testMSG),"test",NULL);
  8. CCMenuItemLabel*labelItem=CCMenuItemLabel::create(CCLabelTTF::create("SendMSG","Arial",26), CCMenu*menu=CCMenu::create(labelItem,NULL);
  9. this->addChild(menu);
  10. bRet=true;
  11. }while(0);
  12. returnbRet;
  13. }
  14. voidHelloWorld::sengMsg(CCObject*pSender)
  15. CCLOG("sendMSG");
  16. CCNotificationCenter::sharedNotificationCenter()->postNotification("test",248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> }
  17. voidHelloWorld::testMSG(CCObject*pSender)
  18. CCLOG("testMSG");
  19. }

现在当我们点击菜单按钮式就可以看到事件被发送和接受的调试信息:



0

猜你在找的Cocos2d-x相关文章