Vec2 origin = Director::getInstance()->getVisibleOrigin();
Size size = Director::getInstance()->getVisibleSize();
auto containerForSprite1 = Node::create();
auto sprite1 = cocos2d::ui::Scale9Sprite::create("CyanSquare.png");
sprite1->setPosition(origin + Vec2(size.width / 2,size.height / 2) + Vec2(-80,80));
containerForSprite1->addChild(sprite1);
addChild(containerForSprite1,10);
auto sprite2 = cocos2d::ui::Scale9Sprite::create("MagentaSquare.png");
sprite2->setPosition(origin + Vec2(size.width / 2,size.height / 2));
addChild(sprite2,20);
auto sprite3 = cocos2d::ui::Scale9Sprite::create("YellowSquare.png");
sprite3->setPosition(Vec2(0,0));
sprite3->setCascadeOpacityEnabled(false);
sprite2->addChild(sprite3,1);
auto listener1 = EventListenerTouchOneByOne::create();//创建一个排队的触控事件监听器 ( 同时仅仅处理一个触控事件 )
listener1->setSwallowTouches(true);////设置是否想下传递触摸
// 当 "swallow touches" 设置为 true,然后,在 onTouchBegan 方法发返回 'true' 将会吃掉触控事件,防止其他监听器使用这个事件.
// 使用 lambda 表达式实现 onTouchBegan 事件的回调函数
listener1->onTouchBegan = [](Touch* touch,Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());////获取精灵对象并取得精灵的矩阵
Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation()); //获取当前触控点相对与按钮的位置
Size s = target->getContentSize();
Rect rect = Rect(0,s.width,s.height);
if (rect.containsPoint(locationInNode))
{
log("sprite began... x = %f,y = %f",locationInNode.x,locationInNode.y);
target->setOpacity(180);
return true;
}
return false;
};
listener1->onTouchMoved = [](cocos2d::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<cocos2d::ui::Scale9Sprite*>(event->getCurrentTarget());
log("onTouchEnded");
target->setOpacity(255);//透明度
if (target == sprite2)
{
containerForSprite1->setLocalZOrder(100);
}
else if (target == sprite1)
{
containerForSprite1->setLocalZOrder(0);
}
};
//// 注册监听器
_eventDispatcher->addEventListenerWithSceneGraPHPriority(listener1,sprite1); _eventDispatcher->addEventListenerWithSceneGraPHPriority(listener1->clone(),sprite2); _eventDispatcher->addEventListenerWithSceneGraPHPriority(listener1->clone(),sprite3); //_eventDispatcher 是 Node 的属性,我们使用它来管理当前节点的所有事件分发(还有像 Scene,Layer,Sprite 等等)。 //在上面的例子中,我们在调用第二和第三个 addEventListenerWithSceneGraPHPriority 中使用 clone() 方法, //这是因为每个事件监听器只能被添加一次。addEventListenerWithSceneGraPHPriority 方法和 addEventListenerWithFixedPriority //在事件监听器中设置一个注册标志,如果已经设置了标志,就不能再次添加了。