Handling touches on child layer Cocos2d-x

1.6k views Asked by At

I've added a layer as a child in a scene. I want when I touch any sprite on this child layer , touch does not go to parent layer. I've written following code for register touch events but touches still going to parent layer, instead of returning back from it.

void onEnter()
{
    Layer::onEnter();

    // Register Touch Event
    auto dispatcher = Director::getInstance()->getEventDispatcher();
    auto listener = EventListenerTouchOneByOne::create();

    listener->setSwallowTouches(true);

    listener->onTouchBegan = CC_CALLBACK_2(onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(onTouchEnded, this);

    dispatcher->addEventListenerWithSceneGraphPriority(listener, _cancelLayer);
}

Here _cancelLayer is name of my child layer. Please someone tell what's wrong with this code? I've not register any touch event with parent layer, but when I touch on parent layer, it still go into touch functions.

Note : Size of child layer is much smaller than parent.

In touchBegin I'm doing nothing , I just want to use it for restricting touches to move onto parent layer.

bool HeaderTableView::onTouchBegan(Touch *pTouch, Event *pEvent)
{
    return true;
}
1

There are 1 answers

4
yangguang1029 On BEST ANSWER

TouchEventListener will response to touchs on the whole screen, so you need to check if the touch is in the bounding box you want,like

bool HeaderTableView::onTouchBegan(Touch *pTouch, Event *pEvent)
{   
    Vec2 touchLocation = pTouch->getLocation(); // Get the touch position
    touchLocation = _cancelLayer->getParent()->convertToNodeSpace(touchLocation);
    Rect bBox = _cancelLayer->getBoundingBox();
    return bBox.containsPoint(touchLocation);
}