cocos2dx 3.0调用点击事件

cocos2dx 3.0调用点击事件
设置可点击

this->setTouchEnabled(true)

1.创建Eventlistener监听器
2.设置该监听器可以向下传递事件

listen->setSwallowTouches(true);

3.添加onTouchesBegan onTouchesCanceled onTouchesMoved onTouchesEnded 等事件的实现,注:必须实现一个,不然会报错,原因是底层判断了如果一个都没有实现就报错(具体看完忘记了。。。),注意onTouchesBegan 的时候会返回一个bool类型,如果为true就不会继续向下传递,如果false就继续往下传递

4.获取全局的事件分发器

EventDispatcher* eventdispatcher = Director::getInstance()->getEventDispatcher();

5.最后将事件监听器注册到该事件分发器中,第二个参数为需要监听的node

this->setTouchEnabled(true);
    EventDispatcher* eventdispatcher = Director::getInstance()->getEventDispatcher();
    auto listen = EventListenerTouchOneByOne::create();
    listen->setSwallowTouches(true);
    //listen->onTouchesBegan = CC_CALLBACK_1(HelloWorld::onTouchBegan,this);
    /*listen->onTouchesBegan = [](Touch* touches, Event  *event) {
        CCLOG("onTouchesBegan!!!!");
    };*/
    auto leftarrow = rootNode->getChildByName("left_arrow");
    auto rightarrow = rootNode->getChildByName("right_arrow");

    CCLOG("left_arrow zooder=%d", leftarrow->getLocalZOrder());

    listen->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
    listen->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
    eventdispatcher->addEventListenerWithSceneGraphPriority(listen, leftarrow);
    eventdispatcher->addEventListenerWithSceneGraphPriority(listen->clone(), rightarrow);

注:在onTouchBegan中获取到的event->getCurrentTarget()不一定是点击到的node,需要自行进行判断,同时确定要不要传到下一层,这样可以确定开始点击的和点击结束的是同个精灵

bool HelloWorld::onTouchBegan(cocos2d::Touch* touches, cocos2d::Event  *event) {
    CCLOG("onTouchesBegan!!!!");
    auto leftarrow = rootNode->getChildByName("left_arrow");
    auto rightarrow = rootNode->getChildByName("right_arrow");
    auto target = static_cast<Sprite*>(event->getCurrentTarget());
    Point p = target->convertToNodeSpace(touches->getLocation());
    Size s = target->getContentSize();
    Rect r = Rect(0, 0, s.width, s.height);
    if (r.containsPoint(p)) {
        if (leftarrow == target) {
            arrow = -1;
            CCLOG("left!!!!");
        }
        if (rightarrow == target) {
            arrow = 1;
            CCLOG("right!!!!");
        }
        return true;
    }
    return false;
}
void HelloWorld::onTouchEnded(cocos2d::Touch* touches, cocos2d::Event  *event) {
    CCLOG("onTouchEnded!!!!");
    auto leftarrow = rootNode->getChildByName("left_arrow");
    auto rightarrow = rootNode->getChildByName("right_arrow");
    auto target = static_cast<Sprite*>(event->getCurrentTarget());
    if (leftarrow == target) {
        arrow = 0;
        return;
    }
    if (rightarrow == target) {
        arrow = 0;
        return;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值