0

我有一个 ui::ScrollView 包含许多精灵。

我创建了每个精灵并通过执行以下操作为每个精灵添加了一个触摸侦听器:

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

4

2 回答 2

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);
}
于 2016-03-22T02:46:42.057 回答
0

cocos2dx 会将 touch-event 分派给每个附加了 touch-event 的 Node,除非有人吞下了它。

但是如果你想让“node”默认判断内容中是否有touch-location,尝试使用“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;
}
于 2016-03-23T10:10:21.293 回答