Cocos2d-x 3.X 事件分发机制

Cocos2d-x 3.X 事件分发机制,第1张

概述介绍 Cocos2d-X 3.X 引入了一种新的响应用户事件机制。 涉及三个基本的方面: Event listeners 封装你的事件处理代码 Event dispatcher 向 listener 分发用户事件 Event 对象 包含关于事件的信息 为了响应事件,首先你要创建一个 EventListener,有五种不同的 EventListener. EventListenerTouch 响应
介绍

Cocos2d-X 3.X 引入了一种新的响应用户事件的机制。

涉及三个基本的方面:

Event Listeners 封装你的事件处理代码 Event dispatcher 向 Listener 分发用户事件 Event 对象 包含关于事件的信息

为了响应事件,首先你要创建一个 EventListener,有五种不同的 EventListener.

EventListenertouch 响应触控事件 EventListenerKeyboard 响应键盘事件 EventListeneracceleration 响应加速事件 EventListenMouse 响应鼠标事件 EventListenerCustom 响应定制的事件

然后,将你的时间处理代码连接到适当的事件监听回调方法中。( 例如 EventListenertouch 的 ontouchBegan ,或者 EventListenerKeyboard 的 onKeypressed )

接着,使用 Eventdispatcher 注册你的 EventListener。

当事件触发之后 ( 例如,用户触摸了屏幕,或者敲击乐键盘 ),Eventdispatcher 通过调用适当的 EventListener 的回调来分发 Event 对象 ( 例如 Eventtouch,或者 EventKeyboard ),每个事件对象包含对应的事件信息 ( 例如包含触控的坐标 )。

示例

在下面的代码中,我们在场景中添加三个按钮,每一个都可以响应触控事件。

auto sprite1 = Sprite::create("Images/CyanSquare.png");sprite1->setposition(origin+Point(size.wIDth/2,size.height/2) + Point(-80,80));addChild(sprite1,10);auto sprite2 = Sprite::create(Images/magentaSquare.png");sprite2->setposition(origin+Point(size.wIDth/2));addChild(sprite2,128); line-height:1.5!important">20);auto sprite3 = Sprite::create(Images/YellowSquare.png");sprite3->setposition(Point(0,128); line-height:1.5!important">0));sprite2->addChild(sprite3,128); line-height:1.5!important">1);  

如图所示

创建一个触控的事件监听器和回调代码

(注意,在下面的代码中,我们使用 C++11 的 Lambda 表达式来实现回调,后面的键盘事件使用另外一种方式,使用 CC_CALLBACK_N 宏来实现)

// 创建一个排队的触控事件监听器 ( 同时仅仅处理一个触控事件 )auto Listener = EventListenertouchOneByOne::create();// 当 "swallow touches" 设置为 true,然后,在 ontouchBegan 方法发返回 'true' 将会吃掉触控事件,防止其他监听器使用这个事件.Listener->setSwallowtouches(true); 使用 lambda 表达式实现 ontouchBegan 事件的回调函数Listener->ontouchBegan = [](touch* touch,Event* event){     event->getCurrentTarget() 返回 *Listener's* sceneGraPHPriority 节点.    auto target = static_cast<Sprite*>(event->getCurrentTarget());    // 获取当前触控点相对与按钮的位置    Point locationInNode = target->convertToNodeSpace(touch->getLocation());    Size s = target->getContentSize();    Rect rect = Rect(0,s.wIDth,s.height);    // 检测点击区域    if (rect.containsPoint(locationInNode))    {        log(sprite began... x = %f,y = %f",locationInNode.x,locationInNode.y);        target->setopacity(180);        return true;    }    false;};// 当移动触控的时候Listener->ontouchmoved = [](touch* touch,255); line-height:1.5!important">event){    auto target = static_cast<Sprite*>(event->getCurrentTarget());    // 移动当前的精灵    target->setposition(target->getposition() + touch->getDelta());};// 结束Listener->ontouchended = [=](touch* touch,255); line-height:1.5!important">event->getCurrentTarget());    log(sprite ontouchesEnded.. ");    target->setopacity(255);    //重新设置 zOrder,改变现实顺序    if (target == sprite)    {        sprite->setZOrder(100);    }    else 0);    }};
添加事件监听器到事件分发器
// 注册监听器_eventdispatcher->addEventListenerWithSceneGraPHPriority(Listener1,sprite1);_eventdispatcher->addEventListenerWithSceneGraPHPriority(Listener1->clone(),sprite2);_eventdispatcher->addEventListenerWithSceneGraPHPriority(Listener1->clone(),sprite3);

_eventdispatcher 是 Node 的属性,我们使用它来管理当前节点的所有事件分发 ( 还有像 Scene,Layer,Sprite 等等 )。

注意,在上面的例子中,我们在调用第二和第三个addEventListenerWithSceneGraPHPriority 中使用 clone() 方法,这是因为每个事件监听器只能被添加一次。addEventListenerWithSceneGraPHPriority 方法和addEventListenerWithFixedPriority 在事件监听器中设置一个注册标志,如果已经设置了标志,就不能再次添加了。

还有需要记住的就是,如果你添加了一个_fixed priority_ Listener 到节点,当节点被删除的时候,你需要手动删除这个监听器,而绑定到节点的_scene graph priority_ Listener,当节点被析构的时候,监听器将会被自动析构。

新的触控机制

上面的处理过程与 2.X版本比较,看起来比较难,在旧版中,你需要从 delegate 类派生,其中定义了 ontouchBegan 等等方法,你的事件处理代码会放到这些委托方法中。

新的事件处理机制将事件处理逻辑从 delegate 中移到了监听器中,上面的逻辑实现了如下功能。

通过使用事件监听器,精灵可以使用 SceneGraPHPriority 添加到事件分发器,也就是说,当点击精灵的时候,回调函数可以以显示的顺序来调用。( 也就是说,显示在前面的精灵优先得到事件 ) 当处理事件逻辑的时候,基于不同的状况来处理触控的逻辑 ( 比如),显示点击的效果。 由于Listener1->setSwallowtouches(true) 设置了,还有在 ontouchBegan 中的处理逻辑,不管何种显示顺序都可以被处理。 FixedPriority 对 SceneGraPHPriority

Eventdispatcher 使用优先级来决定监听器对事件的分发。

FixedPriority ,一个整数,低的 EventListeners 优先高的 EventListenters.

SceneGraPHPriority ,一个节点的指针,高的 Z Order 的节点优先于低的 Z Order 节点,这样确保前面的元素获取触控事件。

其它事件处理模式

下面代码使用另外的机制。

你也可以使用 CC_CALLBACK_N 宏来实现类似机制,下面的代码演示键盘处理。

// 创建键盘监听器 auto Listener = EventListenerKeyboard::create(); Listener->onKeypressed = CC_CALLBACK_2(KeyboardTest::onKeypressed,this); Listener->onkeyreleased = CC_CALLBACK_2(KeyboardTest::onkeyreleased,255); line-height:1.5!important">this); _eventdispatcher->addEventListenerWithSceneGraPHPriority(Listener,255); line-height:1.5!important">this); 实现键盘回调的宏 voID KeyboardTest::onKeypressed(EventKeyboard::KeyCode keyCode,255); line-height:1.5!important">event) { log(Key with keycode %d pressedvoID KeyboardTest::onkeyreleased(EventKeyboard::KeyCode keyCode,0); line-height:1.5!important">Key with keycode %d released Accelerometer 事件

在使用加速事件之前,需要在设备上启用加速。

Device::setAccelerometerEnabled(true);

使用监听器

    auto Listener = EventListeneracceleration::create(CC_CALLBACK_2(AccelerometerTest::onacceleration,255); line-height:1.5!important">this));    _eventdispatcher->addEventListenerWithSceneGraPHPriority(Listener,0); line-height:1.5!important"> 实现回调函数    voID AccelerometerTest::onacceleration(acceleration* acc,255); line-height:1.5!important">event)    {          Processing logic here     }
鼠标事件

在 V3.0 中添加了鼠标点击事件分发,支持多平台,丰富了用户的游戏体验。

与所有的事件类型一样,首先需要创建事件监听器

    _mouseListener = EventListenerMouse::create();    _mouseListener->onMouseMove = CC_CALLBACK_1(MouseTest::onMouseMove,255); line-height:1.5!important">this);    _mouseListener->onmouseup = CC_CALLBACK_1(MouseTest::onmouseup,255); line-height:1.5!important">this);    _mouseListener->onMouseDown = CC_CALLBACK_1(MouseTest::onMouseDown,255); line-height:1.5!important">this);    _mouseListener->onMouseScroll = CC_CALLBACK_1(MouseTest::onMouseScroll,255); line-height:1.5!important">this);    _eventdispatcher->addEventListenerWithSceneGraPHPriority(_mouseListener,255); line-height:1.5!important">this);

然后,一个一个实现监听器的回调函数

voID MouseTest::onMouseDown(Event *event){ EventMouse* e = (EventMouse*)event; string str = Mouse Down detected,Key: "; str += tostr(e->getMousebutton()); ...}voID MouseTest::onmouseup(Event *Mouse Up detected,255); line-height:1.5!important">voID MouseTest::onMouseMove(Event *Mouseposition X:"; str = str + tostr(e->getCursorX()) + Y:" + tostr(e->getCursorY()); voID MouseTest::onMouseScroll(Event *Mouse Scroll detected,X: "; str = str + tostr(e->getScrollX()) + Y: " + tostr(e->getScrollY()); ...} 定制事件

上面的事件是系统定义的事件,事件由系统自动触发,额外的,你也可以定制不是由系统自动触发的事件,通过你自己的代码来实现。

    _Listener = EventListenerCustom::create(game_custom_event1",[=](EventCustom* event){        std::string str(Custom event 1 received,0); line-height:1.5!important">");        char* buf = static_cast<char*>(event->getUserData());        str += buf;        str +=  times";        statusLabel->setString(str.c_str());    });    _eventdispatcher->addEventListenerWithFixedPriority(_Listener,128); line-height:1.5!important">1);

自定义的事件监听器如上所示,有响应代码,添加到事件分发器,如何触发呢?看下面。

    static int count = 0;    ++count;    char* buf = new char[10];    sprintf(buf,0); line-height:1.5!important">%devent(");    event.setUserData(buf);    _eventdispatcher->dispatchEvent(&event);    CC_SAFE_DELETE_ARRAY(buf);

上面的代码创建了一个 EventCustom 对象,设置了用户数据,通过手工调用 _eventdispatcher 的 dispatchEvent 方法触发,这就会触发前面定义的处理器。

删除事件监听器

已经添加的事件监听器可以如下删除。

_eventdispatcher->removeEventListener(Listener);

使用下面的代码,删除所有的事件监听器。

_eventdispatcher->removeAllEventListeners();

当掉用 removeAllEventListeners 的时候,这个节点所有的监听器都被删除了,建议删除特定的监听器。

注意,当调用 removeAll 之后,菜单会停止响应,因为它也需要接收触控事件。

总结

以上是内存溢出为你收集整理的Cocos2d-x 3.X 事件分发机制全部内容,希望文章能够帮你解决Cocos2d-x 3.X 事件分发机制所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1005818.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存