1

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

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

每个精灵?

4

2 回答 2

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

希望,这有帮助。

于 2014-03-11T07:31:51.050 回答
0

是的,您必须为每个精灵添加一个事件监听器,并检测每个精灵的触摸,您必须在触摸开始功能中添加它

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

希望这对你有用

于 2018-06-14T08:14:57.030 回答