cocos2dx 3.0 是利用 setTouchEnabled(bool enable) 注册触摸优先级,但是不能动态更改Widget的触摸优先级,导致在Zorder较低的,动态刷新的,注册有触摸事件的对象可以点透.
因此在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);
}
使用前,必须开启了触摸事件。
源码下载地址:http://www.400gb.com/file/69502408
http://cocos2dx.400gb.com/