// ①创建一个单点触摸事件监听器,处理触摸事件逻辑
auto listener1 = EventListenerTouchOneByOne::create();
// ②设置是否向下传递触摸
listener1->setSwallowTouches(true);
// ③通过 lambda表达式 直接实现触摸事件的响应函数
listener1->onTouchBegan = [](Touch* touch, Event* event){
// 获得当前事件触摸的目标对象
auto target = static_cast<Sprite*>(event->getCurrentTarget());
// 获得当前的触摸点
Point locationInNode = target->convertToNodeSpace(touch->getLocation());
// 获得触摸对象的ContentSize
Size s = target->getContentSize();
// 获得位置矩形
Rect rect = Rect(0, 0, s.width, s.height);
// 如果位置矩形包含触摸点
if (rect.containsPoint(locationInNode))
{
log("onTouchBegan... x = %f, y = %f", locationInNode.x, locationInNode.y);
// 设置透明度
target->setOpacity(180);
// 表明用户触摸事件已经被处理,后续的onTouchMoved、onTouchEnded和onTouchCancelled会接着响应,其他事件监听器则不会再去进行监听本次触摸事件。
return true;
}
return false;
}; 等价于touchListener->onTouchBegan = CC_CallBack_2(HelloWorld::onTouchBegan,this);
void HelloWorld::onTouchBegan(Touch *touch, Event *event){
..........
}
listener1->onTouchMoved = [](Touch* touch, Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
// 移动触摸的精灵
target->setPosition(target->getPosition() + touch->getDelta());
};
listener1->onTouchEnded = [=](Touch* touch, Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
// 设置透明度
target->setOpacity(255);
std::string name;
if (target == sprite2)
{
name = "MagentaSquare.png";
sprite1->setZOrder(100);
subtitle->setString("响应事件的是酒红色滑块,青色滑块的ZOrder值修改为100");
}
else if(target == sprite1)
{
name = "CyanSquare.png";
sprite1->setZOrder(0);
subtitle->setString("响应事件的是青色滑块,青色滑块的ZOrder值修改为0");
}else{
name = "YellowSquare.png";
}
log("onTouchEnded.. 您触摸的是%s",name.c_str());
};
// ④添加场景优先事件监听器。
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1);
//⑤注意:在使用addEventListenerWithSceneGraphPriority或者addEventListenerWithFixedPriority函数时,会对当前使用的事件监听器添加一个已注册的标记,这使得它不能够被添加多次。所以当我们再次使用listener1的时候,需要使用clone()函数创建一个新的克隆。
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite2);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite3);
附加:
target->getBoundingBox().containsPoint(touch->getLocation()))与Point locationInNode = target->convertToNodeSpace(touch->getLocation());
Rect rect1 = Rect(870 - 60*i, 23, 138-60*i, 174);
rect1.containsPoint(locationInNode)之间的区别,前者是触摸范围为目标对象的区域大小,后者是自己自定义的区域大小。