您的位置:首页 > 移动开发 > Cocos引擎

COCOS2D-X之CCNotificationCenter的简单使用Demo

2014-02-12 16:06 525 查看
一、今天我们要讲的是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赶快去下载试试吧


本人郑重声明如下
一、本文来自CSDN博客,传送门:http://BlOG.CSDN.NET/yirancpp
二、All Rights Reserved. 任何个人或网站转载本文时不得移除本声明.
三、不得对文章进行修改,除非明确说明.同时欢迎大家评论转载和分享.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: