首页 > 其他 > 详细

Cocos2D-x游戏开发之二十三:CCNotificationCenter观察者模式(2)-不同层之间事件的发送和接受

时间:2014-04-14 01:41:54      阅读:535      评论:0      收藏:0      [点我收藏+]

刚才我们 学习了基本的CCNotificationCenter观察者模式在一个层之中监听事件,现在我们再进一步学习如何在不同层之间监听吧,这一节的知识点我们在HelloWorld中发送一个事件消息在OtherLayer中接受并且处理消息。其实很简单只是一个函数换了个位置而已,直接上代码吧:

class HelloWorld : public cocos2d::CCLayer
{
public:
    virtual bool init();  
    static cocos2d::CCScene* scene();
   	void  sengMsg(CCObject *pSender);
	//void testMSG(CCObject *pSender);将此函数搬到OtherLayer中
    CREATE_FUNC(HelloWorld);
};
HelloWorld的实现:
bool HelloWorld::init()
{
    bool bRet = false;
    do 
    {
        //////////////////////////////////////////////////////////////////////////
        // super init first
        //////////////////////////////////////////////////////////////////////////

        CC_BREAK_IF(! CCLayer::init());
		CCMenuItemLabel *labelItem = CCMenuItemLabel::create(CCLabelTTF::create("Send MSG","Arial",26),this,menu_selector(HelloWorld::sengMsg));
		CCMenu *menu = CCMenu::create(labelItem,NULL);
		this->addChild(menu);
        bRet = true;
    } while (0);

    return bRet;
}
void HelloWorld::sengMsg(CCObject *pSender)
{
	CCLOG("HelloWorld sendMSG");
	CCNotificationCenter::sharedNotificationCenter()->postNotification("test",NULL);
}
OtherLayer层的实现:

#include "cocos2d.h"
using namespace  cocos2d;
class OtherLayer :	public CCLayer
{
public:
CREATE_FUNC(OtherLayer);
virtual bool init();
private:
void testMSG(CCObject *pData);
};

bool OtherLayer::init()
{
	CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(OtherLayer::testMSG),"test",NULL);
	return true;
}
void OtherLayer::testMSG(CCObject *pDATA)
{
	CCLOG("OtherLayerMSG");
}

最后一件很重要的事情就是在HelloWorld的Scene中添加OtherLayer

CCScene* HelloWorld::scene()
{
    CCScene * scene = NULL;
    do 
    {
        // ‘scene‘ is an autorelease object
        scene = CCScene::create();
        CC_BREAK_IF(! scene);

        // ‘layer‘ is an autorelease object
        HelloWorld *layer = HelloWorld::create();
        CC_BREAK_IF(! layer);
		OtherLayer *otherlayer = OtherLayer::create();
        // add layer as a child to scene
        scene->addChild(layer);
		scene->addChild(otherlayer);
    } while (0);

    // return the scene
    return scene;
}

现在我们的所有code部分已经完成看效果吧:


bubuko.com,布布扣

Cocos2D-x游戏开发之二十三:CCNotificationCenter观察者模式(2)-不同层之间事件的发送和接受,布布扣,bubuko.com

Cocos2D-x游戏开发之二十三:CCNotificationCenter观察者模式(2)-不同层之间事件的发送和接受

原文:http://blog.csdn.net/vanquishedzxl/article/details/23618125

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!