Cocos2d-x之自定义事件

网友投稿 687 2022-05-28

系统定义的事件,如触摸事件、键盘事件等都是被系统自动触发的。除了使用系统定义的事件之外,我们还可以自定义一些事件,它们就不是由系统来触发了,而是由我们自己写的代码来触发,如:

_listener = EventListenerCustom::create("game_custom_event1", [=](EventCustom* event){ std::string str("Custom event 1 received, "); char* buf = static_cast(event->getUserData()); str += buf; str += " times"; statusLabel->setString(str.c_str()); }); _eventDispatcher->addEventListenerWithSceneGraphPriority(_listener, this);

1

2

3

4

5

6

7

8

9

上面自定义了事件监听器,还有一个响应的方法,并被添加到了事件分发器event

dispatcher中。触发方式如下:

static int count = 0; ++count; char* buf[10]; sprintf(buf, "%d", count); EventCustom event("game_custom_event1"); event.setUserData(buf); _eventDispatcher->dispatchEvent(&event);

1

2

3

Cocos2d-x之自定义事件

4

5

6

7

8

9

10

上面这个例子创建了一个EventCustom对象,并设置它的UserData。然后通过 _eventDispatcher->dispatchEvent(&event)进行手动分发。这就触发了之前定义的事件处处理程序。处理程序被立即调用,因此可以使用本地堆栈变量作为用户数据。

Cocos2D

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:152.利用图形页实现动画
下一篇:Android之什么时候调用onSaveInstance方法的时候(为什么按Home键盘会调用,按Back不调用)
相关文章