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){

}

 

posted @ 2016-12-22 17:29 HaoK 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值