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

刚才我们 学习了基本的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部分已经完成看效果吧:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值