首页 > 代码库 > cocos2dx 3.x 精灵重叠时点击最上层的精灵

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 精灵重叠时点击最上层的精灵