c++ - 我是否需要为每个要检测的 Sprite 设置 addEventListenerWithSceneGraphPriority?

标签 c++ cocos2d-x cocos2d-x-3.0

我想检测哪个 Sprite 被触摸了。 如果我这样做:

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

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

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

Sprite 检测正常。

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

_eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), mySprite);

对于每个 Sprite ?

最佳答案

不,您不需要为所有 Sprite 添加 eventListener。

您需要一个 Sprite 父节点的事件监听器。

试试这个:

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

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

希望这对您有所帮助。

关于c++ - 我是否需要为每个要检测的 Sprite 设置 addEventListenerWithSceneGraphPriority?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21475075/

相关文章:

c++ - 在 cocos2d-x 3 中异步预加载 spritsheet 并使用它

c++ - Cocos2d-x network::HttpRequest - 为什么我应该将 Layer* 传递给 setResponseCallback?

c++ - 无法在cocos2dx中显示Menu MenuItemImage

c++ - C++ 中的信号处理

c++ - 在 VS2019 或 VSCode 中使用 Unreal Engine 4.24.2 时,如何修复这些错误的 Intellisense 错误?

c++ - 从 AllocConsole C++ 获取行输入

c# - 运行程序需要哪些 C++ 包?

javascript - 序列结束后切换场景

android - 我如何使用 Cocos2d-x 制作类范围的 CCArray?

c++ - stringstream << 运算符在循环中消耗大量内存