如何让精灵吞下所有触碰

cocos2d-x 3 How to make sprite swallow all touches only on it

本文关键字:精灵      更新时间:2023-10-16

我有一个main layer应该得到触摸事件。但在那一层有一个navigation bar,其中有按钮和其他精灵,是cocos2d::Sprite的子类。现在我需要所有对navigation bar的触摸都不能被解释为对main layer的触摸。按钮正常工作,但navigation bar精灵将触摸传递给main layer。我这样做是为了防止传递事件:

auto touchListenerOneByOne = EventListenerTouchOneByOne::create();
touchListenerOneByOne->setSwallowTouches(true);
touchListenerOneByOne->onTouchBegan = CC_CALLBACK_2(NavigationBar::onBoardTouchBegan, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListenerOneByOne, this);

bool NavigationBar::onBoardTouchBegan(Touch* touch, Event* event)
{
    CCLOG("Navigation sprite is touched......!");
    return true;
}

这可以阻止传递,但它会阻塞-吞噬所有的触摸。现在我不能传递任何触摸到main layer,即使我不触摸navigation bar。我试图使用setContentSize,但它没有帮助。解决方案在哪里?

答案在这里:http://www.cocos2d-x.org/wiki/How_To_Subclass_Sprite_And_Add_Event_Listeners

我在这里修改了以下内容:

  • Vector2 to Vec2
  • 删除void touchEvent(cocos2d::Touch* touch, cocos2d::Vector2 _p);
  • 中的第二个参数
  • MySprite::touchEvent(touch);touchEvent(touch);
  • cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener, 30);_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

这使得精灵应该检查触摸是否在它上面,然后在onTouchBegan监听器中返回true,否则返回false