Node对象外部的触摸也响应了触摸事件

时间:2015-03-25 14:24:27

标签: cocos2d-iphone cocos2d-x

在我的代码中,我添加了两个精灵,其类型为.png,大小为110 * 150。每个精灵都会分配两个触摸侦听器。不知何故,无论我触摸到哪里,listerner2和听众都会响应,即使我触出了精灵,无论我触摸到哪里,代码都会打印listener2listener1,我的代码有什么问题?

Scene* DemoScene::create()
{
    auto demoScene = Scene::create();

    if (demoScene == NULL) {
        return NULL;
    }



    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    auto demoSprite = Sprite::create("1.png");
    demoSprite->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height/2));
    demoScene->addChild(demoSprite);



    auto demoSprite2 = Sprite::create("1.png");
    demoSprite2->setPosition(Vec2(origin.x + visibleSize.width/3, origin.y + visibleSize.height/3));
    demoScene->addChild(demoSprite2);



    auto listener = EventListenerTouchOneByOne::create();
//    listener->setSwallowTouches(true);
    listener->onTouchBegan = [](Touch *touch, Event *event){
        printf("listener1");
        return true;
    };

    auto listener2 = EventListenerTouchOneByOne::create();
//    listener2->setSwallowTouches(true);
    listener2->onTouchBegan = [](Touch *touch, Event *event){
        printf("listener2");
        return true;
    };



    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, demoSprite);
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener2, demoSprite2);


    return demoScene;

}

1 个答案:

答案 0 :(得分:1)

事件监听器不检查水龙头是否在Sprite内部。你应该手动控制它。如果触摸了demoSprite,则在onTouchBegan方法上返回true将阻止将触摸传播到其他侦听器。 (如果燕子触摸设置为true)

auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = [](Touch *touch, Event *event){

    // check if the touch is inside the target
    Vec2 locationInNode = event->getCurrentTarget()->convertToNodeSpace(touch->getLocation());
    Size s = event->getCurrentTarget()->getContentSize();
    Rect rect = Rect(0,0, s.width, s.height);

    if (rect.containsPoint(locationInNode)) {
        printf("listener1");
        return true;
    }

    return false;
};


auto listener2 = EventListenerTouchOneByOne::create();
listener2->setSwallowTouches(true);
listener2->onTouchBegan = [](Touch *touch, Event *event){

    // check if the touch is inside the target
    Vec2 locationInNode = event->getCurrentTarget()->convertToNodeSpace(touch->getLocation());
    Size s = event->getCurrentTarget()->getContentSize();
    Rect rect = Rect(0,0, s.width, s.height);

    if (rect.containsPoint(locationInNode)) {
        printf("listener2");
        return true;
    }

    return false;
};