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

来源:未知 责任编辑:责任编辑 发表时间:2014-05-10 12:18 点击:

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

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

class HelloWorld : public cocos2d::CCLayer
{
public:
    virtual bool init();  
    static cocos2d::CCScene* scene();
   	void  sengMsg(CCObject *pSender);
	void testMSG(CCObject *pSender);
    CREATE_FUNC(HelloWorld);
};

#endif  // __HELLOWORLD_SCENE_H__

然后在init()函数中添加事件的监听。在SendMSG()函数中发送事件消息。

bool HelloWorld::init()
{
    bool bRet = false;
    do 
    {
        //////////////////////////////////////////////////////////////////////////
        // super init first
        //////////////////////////////////////////////////////////////////////////

        CC_BREAK_IF(! CCLayer::init());
		CCNotificationCenter::sharedNotificationCenter()->addObserver(this,callfuncO_selector(HelloWorld::testMSG),"test",NULL);
		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("sendMSG");
	CCNotificationCenter::sharedNotificationCenter()->postNotification("test",NULL);
}
void HelloWorld::testMSG(CCObject *pSender)
{
	CCLOG("testMSG");
}

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

\


    发表评论
    请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
    用户名: 验证码:点击我更换图片
    最新评论 更多>>

    推荐热点

    • cocos2d-x学习笔记(19)--label 、label atlas
    • cocos2d-x学习笔记(23)--地图的使用3--CCTMXLayer
    • Cocos2d-x学习(一):HelloWorld
    • cocos2dx在xcode下开发,编译到android上(2)
    • cocos2d 设置屏幕默认方向
    • cocos2d-x学习笔记(22)--地图的使用2(TMX) --Z-Order、AnchorPoi
    • Cocos2d-x 2.0 之 Actions “三板斧” 之一
    • cocos2d-x学习笔记(18)--游戏打包(windows平台)
    • cocos2d-x学习笔记(16)--spritesheet(精灵表单)
    网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
    Copyright © 2008-2015 计算机技术学习交流网. 版权所有

    豫ICP备11007008号-1