加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 19:12:31 所属栏目:百科 来源:网络整理
导读:介绍 Cocos2d-X 3.X 引入了一种新的响应用户事件的机制。 涉及三个基本的方面: Event listeners 封装你的事件处理代码 Event dispatcher 向 listener 分发用户事件 Event 对象 包含关于事件的信息 为了响应事件,首先你要创建一个 EventListener,有五种不


介绍

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 中移到了监听器中,上面的逻辑实现了如下功能。

  1. 通过使用事件监听器,精灵可以使用 SceneGraphPriority 添加到事件分发器,也就是说,当点击精灵的时候,回调函数可以以显示的顺序来调用。( 也就是说,显示在前面的精灵优先得到事件 )
  2. 当处理事件逻辑的时候,基于不同的状况来处理触控的逻辑 ( 比如),显示点击的效果。
  3. 由于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 之后,菜单会停止响应,因为它也需要接收触控事件。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读