码迷,mamicode.com
首页 > 其他好文 > 详细

cocos2dx 3.x 精灵重叠时点击最上层的精灵

时间:2016-12-22 20:07:23      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:add   one   set   box   end   触摸事件   上层   pos   get   

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

标签:add   one   set   box   end   触摸事件   上层   pos   get   

原文地址:http://www.cnblogs.com/H-K-Home/p/6212109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!