在cocos2dx3.0中是使用setTouchEnabled(bool enable) 注册触摸优先级,但是widget不会自动屏蔽下层触摸做动态刷新,然后今天给大家分享下Widget 动态设置触摸优先级,从而方便屏蔽下方界面 。

因此在Widget.h和Widget.cpp添加方法:


void Widget::setTouchPriority(int priority)
{
    _touchPriority = priority;

    for (auto& child : _children)
    {
        if (child)
        {
            Widget* widgetChild = dynamic_cast<Widget*>(child);
            if (widgetChild)
            {
                widgetChild->setTouchPriority(this->getTouchPriority()-1);
            }
        }
    }

    if (!_touchEnabled)
        return;
    
    _eventDispatcher->removeEventListener(_touchListener);
    CC_SAFE_RELEASE_NULL(_touchListener);

    _touchListener = EventListenerTouchOneByOne::create();
    CC_SAFE_RETAIN(_touchListener);
    _touchListener->setSwallowTouches(true);
    _touchListener->onTouchBegan = CC_CALLBACK_2(Widget::onTouchBegan, this);
    _touchListener->onTouchMoved = CC_CALLBACK_2(Widget::onTouchMoved, this);
    _touchListener->onTouchEnded = CC_CALLBACK_2(Widget::onTouchEnded, this);
    _touchListener->onTouchCancelled = CC_CALLBACK_2(Widget::onTouchCancelled, this);
    _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, _touchPriority);

}

使用前,必须开启了触摸事件。