一、今天我们要讲的是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赶快去下载试试吧
本文介绍如何使用CCNotificationCenter类实现观察者模式,使精灵响应触屏事件并移动到点击位置。文章提供了一个简单示例,展示了如何创建观察者、触发通知及响应处理。

被折叠的 条评论
为什么被折叠?



