2016-03-21 34 views
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); 
} 

的问题是,如果我点击任何地方在屏幕上,它似乎触发所有的触摸事件在循环中创建的精灵。在创建监听器的过程中是否存在某些不正确的问题,或者是否与ui :: ScrollView中的触摸有冲突?

我用V 3.10

回答

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); 
} 
0

cocos2dx会将触摸事件分派给附加触摸事件的每个节点,除非有人吞下它。

但是,如果您希望“节点”默认判断内容中是否有触摸位置,请尝试使用带有“addTouchEventListener”的“UIWidget”。它会自行计算。

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; 
}