我需要为每个要检测的精灵设置 addEventListenerWithSceneGraphPriority 吗?

use*_*898 1 c++ cocos2d-x cocos2d-x-3.0

我想检测哪个精灵被触摸。如果我做 :

auto listener = EventListenerTouchOneByOne::create(); 
listener->setSwallowTouches(true);   
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), mySprite);
Run Code Online (Sandbox Code Playgroud)

然后在我的触摸方法中我这样做:

bool HelloWorld::onTouchBegan(Touch* touch, Event* event)
auto spriteBlock = static_cast<Block*>(event->getCurrentTarget());
Run Code Online (Sandbox Code Playgroud)

精灵被很好地检测到。

问题是我在图层上有大约 20 个精灵,我需要能够检测到它们,我需要设置吗

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), mySprite);
Run Code Online (Sandbox Code Playgroud)

对于每个精灵?

Rol*_*nyi 5

不,您不需要向所有精灵添加事件监听器。

您需要一个精灵父节点的事件侦听器。

尝试这个:

bool HelloWorld::onTouchBegan(Touch *touch, Event *event) {
    Node *parentNode = event->getCurrentTarget();
    Vector<Node *> children = parentNode->getChildren();
    Point touchPosition = parentNode->convertTouchToNodeSpace(touch);
    for (auto iter = children.rbegin(); iter != children.rend(); ++iter) {
        Node *childNode = *iter;
        if (childNode->getBoundingBox().containsPoint(touchPosition)) {
            //childNode is the touched Node
            //do the stuff here
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

它以相反的顺序迭代,因为您将触摸具有最高 z-index 的精灵(如果它们重叠)。

希望,这有帮助。