一、今天我们要讲的是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赶快去下载试试吧
COCOS2D-X之CCNotificationCenter的简单使用Demo
原文:http://blog.csdn.net/yirancpp/article/details/19121137