一、Cocos2d 2.x触摸事件(实现两点)
1、在onEnter中加入触摸事件派发器,并且优先级要比下层高(即nPriority较小),同时设置bSwallowsTouches为true(即阻止触摸事件继续派发),然后在onExit中移除派发器。
void TouchNode::onEnter()
{
CCNode::onEnter();
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, nPriority, bSwallowsTouches);
}
void TouchNode::onExit()
{
CCNode::onExit();
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
}
2、CCNode节点继承实现CCTouchDelegate类中的ccTouchBegan、ccTouchMoved、ccTouchEnded函数。
如果ccTouchBegan函数返回true,则屏蔽该节点以下的层,如果返回false,则不屏蔽并且不会进入ccTouchMoved和ccTouchEnded。
bool TouchNode::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
return true;
}
二、Cocos2d 3.x触摸事件(实现两点)
1、设置setSwallowTouches为true则通过onTouchBegan选择性屏蔽下层,返回false则不屏蔽
2、为Node节点的_eventDispatcher添加事件监听器,以下代码实现屏蔽TouchNode节点以内的下层Layer,onTouchBegan回调如果返回true屏蔽下层触摸,返回false则不屏蔽。
auto colorLayer = LayerColor::create(ccc4(60, 60, 60, 200));
colorLayer->ignoreAnchorPointForPosition(false);
colorLayer->setAnchorPoint(Vec2(0.5, 0.5));
colorLayer->setContentSize(Size(200, 200));
addChild(colorLayer);
auto onTouchBegan = [=](Touch* touch, Event* event)
{
auto target = event->getCurrentTarget();
auto touchPos = target->convertToNodeSpace(touch->getLocation());
auto rect = colorLayer->boundingBox();
if (rect.containsPoint(touchPos))
{
log("node touch================");
return true;
}
return false;
};
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = onTouchBegan;
listener->setSwallowTouches(true);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);