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

时间:2014-01-31 08:00:33

标签: 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);

然后用我的触摸方法:

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

精灵检测不到。

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

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

每个精灵?

2 个答案:

答案 0 :(得分:4)

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

您需要为精灵的父节点提供事件侦听器。

试试这个:

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

希望,这有帮助。

答案 1 :(得分:0)

是您必须为每个精灵添加一个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;
}

希望这适合你