我有一个包含许多精灵的ui :: ScrollView。
我创建了每个sprite,并通过执行以下操作为每个sprite添加了一个触摸侦听器:
for(int i=0; i < 5; i++){
Sprite* foo = Sprite::createWithSpriteFrameName("foo");
myScrollView->addChild(foo);
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [this,somestring](Touch* touch, Event* event){
......some code
};
listener->onTouchMoved = [foo,this,somestring](Touch* touch, Event* event){
......some code
};
listener->onTouchEnded = [foo,this,somestring](Touch* touch, Event* event){
......some code
};
foo->getEventDispatcher->addEventListenerWithSceneGraphPriority(listener1,foo);
}
问题是,如果我点击屏幕上的ANYWHERE,它似乎会触发循环中创建的所有精灵的触摸事件。我是如何创建监听器的,或者是否与ui :: ScrollView中的触摸有冲突?
我正在使用v 3.10
答案 0 :(得分:0)
因为这就是TouchListener在cocos2d-x中的工作方式。除非有人吞下触摸事件,否则将调用所有触摸侦听器。你的代码是:
auto touchSwallower = EventListenerTouchOneByOne::create();
touchSwallower ->setSwallowed(true);
touchSwallower->onTouchBegan = [](){ return true;};
getEventDispatcher->addEventListenerWithSceneGraphPriority(touchSwallower ,scrollview);
for(int i=0; i < 5; i++){
Sprite* foo = Sprite::createWithSpriteFrameName("foo");
myScrollView->addChild(foo);
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowed(true);
listener->onTouchBegan = [this,somestring](Touch* touch, Event* event){
......some code
Vec2 touchPos = myScrollView->convertTouchToNodeSpace(touch);
return foo->getBoundingBox()->containsPoint(touchPos);
};
listener->onTouchMoved = [foo,this,somestring](Touch* touch, Event* event){
......some code
};
listener->onTouchEnded = [foo,this,somestring](Touch* touch, Event* event){
......some code
};
foo->getEventDispatcher->addEventListenerWithSceneGraphPriority(listener1,foo);
}
答案 1 :(得分:0)
cocos2dx会将触摸事件发送给附加触摸事件的每个节点,除非有人吞下它。
但是如果你想让“node”默认判断内容中是否触摸位置,请尝试将“UIWidget”与“addTouchEventListener”一起使用。它将自行计算。
bool Widget::onTouchBegan(Touch *touch, Event *unusedEvent)
{
_hitted = false;
if (isVisible() && isEnabled() && isAncestorsEnabled() && isAncestorsVisible(this) )
{
_touchBeganPosition = touch->getLocation();
auto camera = Camera::getVisitingCamera();
if(hitTest(_touchBeganPosition, camera, nullptr))
{
if (isClippingParentContainsPoint(_touchBeganPosition)) {
_hittedByCamera = camera;
_hitted = true;
}
}
}
if (!_hitted)
{
return false;
}
setHighlighted(true);
/*
* Propagate touch events to its parents
*/
if (_propagateTouchEvents)
{
this->propagateTouchEvent(TouchEventType::BEGAN, this, touch);
}
pushDownEvent();
return true;
}