cocos2dx 3.x 精灵重叠时点击最上层的精灵
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cocos2dx 3.x 精灵重叠时点击最上层的精灵相关的知识,希望对你有一定的参考价值。
ps. 这个方法只适用设置精灵的触摸..
//注册触摸事件..3.X后可以在这样写..不需要重新声明 EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [](Touch* pTouch, Event* pEvent){ return true; }; listener->onTouchMoved = [](Touch* pTouch, Event* pEvent){ }; listener->onTouchEnded = [](Touch* pTouch, Event* pEvent){ }; //注册精灵监听..第1个精灵和第2个精灵 _eventDispatcher->addEventListenerWithSceneGraphpriority(listener, spr); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), spr1);
另一种写法
//创建精灵 Size size = Director::getInstance()->getWinSize(); Sprite* sp1 = Sprite::create("sprite1.png"); sp1->setPosition(Point(size.width * 0.5f, size.height * 0.5f)); this->addChild(sp1); Sprite* sp2 = Sprite::create("sprite2.png"); sp2->setPosition(Point(size.width * 0.5f, size.height * 0.5f)); this->addChild(sp2); //注册触摸 EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan,this); listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved,this); listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded,this); listener->setSwallowTouches(true); //注册精灵监听 _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, sp1); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener->clone(), sp2);
bool HelloWorld::onTouchBegan(cocos2d::Touch *pTouch, cocos2d::Event *pEvent){ //获取当前点击的精灵 Sprite* target = static_cast<Sprite*>(pEvent->getCurrentTarget()); if (target->getBoundingBox().containsPoint(pTouch->getLocation())) return true;//点击到了 return false; }
void HelloWorld::onTouchMoved(cocos2d::Touch *pTouch, cocos2d::Event *pEvent){ Sprite* target = static_cast<Sprite*>(pEvent->getCurrentTarget()); //触摸的图片移动 target->setPosition(target->getPosition() + pTouch->getDelta()); } void HelloWorld::onTouchEnded(cocos2d::Touch *pTouch, cocos2d::Event *pEvent){ }
以上是关于cocos2dx 3.x 精灵重叠时点击最上层的精灵的主要内容,如果未能解决你的问题,请参考以下文章
cocos2dx 3.x(点击屏幕移动精灵,拖动精灵)不需要写回调函数
cocos2dx 3.x(移动修改精灵坐标MoveTo与MoveBy)