首页 > 其他 > 详细

COCOS2D-X之CCNotificationCenter的简单使用Demo

时间:2014-02-13 01:47:15      阅读:405      评论:0      收藏:0      [点我收藏+]

一、今天我们要讲的是CCNotificationCenter这个类.这是一个实现观察者模式的类,掌握这个类的用法还是很有用处的.今天这个Demo要实现的效果是通过将触屏消息发送给观察者以使之移动精灵的位置到鼠标点击的地方.代码如下:

#define ObserverName "BOSS"//定义观察者的名字
bool HelloWorld::init()
{
 CCLayer::init();
 CCSprite* pBoss = CCSprite::create("Spr.png");
 CCSize szWin = CCDirector::sharedDirector()->getWinSize();
 pBoss->setPosition(CCPointMake(szWin.width/2,szWin.height/2));
 this->addChild(pBoss,0,1000);
 CCNotificationCenter::sharedNotificationCenter()->addObserver(this, callfuncO_selector(HelloWorld::ObserverCallback),ObserverName, NULL);
 setTouchEnabled(true);
 return true;
}
HelloWorld::~HelloWorld()
{
 CCNotificationCenter::sharedNotificationCenter()->removeObserver(this,"removeObserver");//移除观察者
}
void HelloWorld::ObserverCallback(CCObject* pSender)
{
 CCNode* pNode = static_cast<CCNode *>(pSender);
 switch(pNode->getTag())
 {
 case 100:
  this->getChildByTag(1000)->setPosition(pNode->getPosition());
 }
}

bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
 CCPoint pt = pTouch->getLocation();
 CCNode* pNode = CCNode::create();
 pNode->setPosition(pt);
 pNode->setTag(100);//可以用Tag来表示不同的消息
 CCNotificationCenter::sharedNotificationCenter()->postNotification(ObserverName,pNode);
 return true;
}
OK就是这么简单最后附上工程的下载地址http://t.cn/zOAuvxW赶快去下载试试吧bubuko.com,布布扣
本人郑重声明如下 一、本文来自CSDN博客,传送门:http://BlOG.CSDN.NET/yirancpp 二、All Rights Reserved. 任何个人或网站转载本文时不得移除本声明. 三、不得对文章进行修改,除非明确说明.同时欢迎大家评论转载和分享.

COCOS2D-X之CCNotificationCenter的简单使用Demo

原文:http://blog.csdn.net/yirancpp/article/details/19121137

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