我是否需要为每个要检测到的每个精灵设置AddEventListenerWithSceneGrapriority

Do I need to set addEventListenerWithSceneGraphPriority for each sprite I want to detect?

本文关键字:精灵 设置 AddEventListenerWithSceneGrapriority 检测 是否      更新时间:2023-10-16

我想检测到触摸了哪个精灵。如果我这样做:

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

发现精灵的良好。

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

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

每个精灵?

不,您不需要将EventListener添加到所有精灵中。

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

尝试以下操作:

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索引的精灵(如果它们重叠)。

希望,这个帮助。

是的,您必须向每个精灵添加一个eventlistener并检测每个触摸您必须在触摸中添加此功能

bool OwlStoryScene0::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) {
        cocos2d::Touch *touched = (Touch *) touch;
        Point location = touched->getLocationInView();
        location = Director::getInstance()->convertToGL(location);
        auto target = static_cast<Sprite*>(event->getCurrentTarget());
        Point locationInNode = target->convertToNodeSpace(touch->getLocation());
        Size s = target->getContentSize();
        Rect rect = Rect(0, 0, s.width, s.height);
        if (rect.containsPoint(locationInNode)  && target == SPRITE) {
            //DoSomething
        }
        else if (rect.containsPoint(locationInNode) && target == SPRITE) {
            //DoSomething
        }
    return false;
}

希望这对您有用