Cocos2dx 3.1事件监听
1、新建一个存放数据的类
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
class AAA
{
public:
CC_SYNTHESIZE(std::string, name, Name);
CC_SYNTHESIZE(int, age, Age);
~AAA(){ CCLOG("delete"); }
};
2、新建一个”yang”的监听器,
方式1:利用C++lambda表达式
[html] view plaincopy在CODE上查看代码片派生到我的代码片
auto myListener = EventListenerCustom::create("yang", [=](EventCustom* event){
AAA* b = (AAA*)(event->getUserData());
CCLOG("getUserDate: name=%s , age=%d", b->getName().c_str(), b->getAge());
delete b;
});
//委派这个监听器,_eventDispatcher是Node类上的成员变量,继承后可以直接使用
_eventDispatcher->addEventListenerWithFixedPriority(myListener, 1);
方式2:回调函数方式
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
auto myListener = EventListenerCustom::create("yang", CC_CALLBACK_1(HelloWorld::myEventCustom,this));
//分配这个监听器
_eventDispatcher->addEventListenerWithFixedPriority(myListener, 1);
void HelloWorld::myEventCustom(EventCustom* event)
{
AAA* b = (AAA*)(event->getUserData());
CCLOG("getUserDate: name=%s , age=%d", b->getName().c_str(), b->getAge());
delete b;
}
3、创建事件yang并添加数据,就可以通知yang监听器并获取数据
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
if (count == 3)
{
AAA a;
a.setName("myname");
a.setAge(8);
EventCustom event("yang");
event.setUserData(&a);
//分配事件
_eventDispatcher->dispatchEvent(&event);
}
这事件的创建我写在定时器里,count每秒+1;当满足条件时就创建这个yang时间
运行结果:
getUserDate: name=myname , age=8
delete
Cocos2dx 3.1消息通知
1、在消息中心添加一个要监听的消息xuan,回调函数是ShowGameOver,传递到回调函数的参数是NULL
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
//监听一个xuan的消息,回调函数是ShowGameOver,
NotificationCenter::getInstance()->addObserver(this, callfuncO_selector(HelloWorld::ShowGameOver), "xuan", NULL);
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
void HelloWorld::ShowGameOver(Ref* pObj)
{
if (pObj != NULL)
{
auto sp = (Sprite*)pObj;
CCLOG("Game over ! tag=%d", sp->getTag());
}
}
2、往消息中心发送一个xuan消息,传递参数为sp(参数必须为Ref的子类)
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
if (count == 6)
{
auto sp = Sprite::create("HelloWorld.png");
sp->setTag(180);
//发送一个xuan的消息,参数为sp,第二个参数必须是Ref的子类
NotificationCenter::getInstance()->postNotification("xuan", sp);
}
3、运行结果
Game over ! tag=180
4、必须注意的问题
NotificationCenter::getInstance()->addObserver(this,callfuncO_selector(HelloWorld::ShowGameOver),"xuan",NULL);
NotificationCenter::getInstance()->postNotification("xuan",sp);
监听器和发射器的最后一个参数必须有一个为NULL,不然回调函数获取不到传递的参数,两个参数不知获取那个。
哪个不为NULL就获取哪个。
事件监听和消息通知的区别
区别在于传递的参数,事件监听可以传递任意类型的参数,而消息通知必须传递Ref的子类,也就是cocos2dx里面的object类