按钮的EventListener

时间:2015-02-17 16:17:05

标签: c++ cocos2d-x box2d event-listener

我正在使用Cocos2d-x开发2D汽车游戏,我遇到了问题。 我想使用Box2D来简化碰撞和移动管理,但在此之前我想让我的4个按钮工作。 关键是我有类似的东西

RaceScene.cpp

bool Race::init() {
    //...
    auto forwardArrow = MenuItemImage::create("forward_arrow.png", "forward_arrow.png", CC_CALLBACK_1(Race::forward, this));
    forwardArrow->setAnchorPoint(Vec2(0,0));

    forwardArrow->setPosition(Vec2(origin.x + visibleSize.width - forwardArrow->getContentSize().width*1.2 ,
                            origin.y + forwardArrow->getContentSize().height));
    //...
}

void Race::forward(Ref* pSender)
{
    /*MessageBox("YOU PRESSED THE FORWARD BUTTON","Alert");*/
}

但是我注意到这不是方法,因为我不能同时按下多个按钮,也不能根据按下按钮的时间来改变速度。

所以我用Google搜索并检查了Cocos文档,并且每个人都在讨论EventListeners,但我找不到如何将其添加到我的问题中。

我不需要处理屏幕触摸,我需要处理每个按钮触摸。

感谢。

1 个答案:

答案 0 :(得分:1)

因此,经过几个小时的研究和尝试,以及从Cocos2d-x论坛获得一些帮助,我得到了解决方案。


<强> RaceScene.cpp

bool Race::init() {
    ...
    forwardArrow = Sprite::create("forward_arrow.png");
    forwardArrow->setAnchorPoint(Vec2(0,0));

    forwardArrow->setPosition(Vec2(origin.x + visibleSize.width - forwardArrow->getContentSize().width*1.2 ,
                            origin.y + forwardArrow->getContentSize().height));
    this->addChild(forwardArrow);

    ...

    auto listenerForwardButton = EventListenerTouchOneByOne::create();
    listenerForwardButton->setEnabled(true);
    listenerForwardButton->setSwallowTouches(true);

    listenerForwardButton->onTouchBegan = CC_CALLBACK_2(Race::onTouchesForwardBegan, this);
    // trigger when you let up
    listenerForwardButton->onTouchEnded = CC_CALLBACK_2(Race::onTouchesForwardEnded, this);

    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, forwardArrow);
}

bool Race::onTouchesForwardBegan(cocos2d::Touch* touch, cocos2d::Event* event)
{
    Vec2 touchPoint = touch->getLocation();
    Rect boundingBoxArrow = this->forwardArrow->getBoundingBox();

    if (boundingBoxArrow.containsPoint(touchPoint)){
        return true;
    }
    return false;
}

void Race::onTouchesForwardEnded(cocos2d::Touch* touch, cocos2d::Event* event)
{
    cocos2d::log("You touched %f, %f", touch->getLocationInView().x, touch->getLocationInView().y);
    MessageBox("YOU PRESSED THE FORWARD BUTTON","Alert");
    auto forward = MoveBy::create(1,Vec2(-5,0));
    mainSprite->runAction(forward);
}

<强> RaceScene.h

class Race : public cocos2d::Layer {
    public:
        virtual bool init();
        cocos2d::Sprite* forwardArrow;
        ...
    private:
        bool onTouchesForwardBegan(cocos2d::Touch* touch, cocos2d::Event* event);
        void onTouchesForwardEnded(cocos2d::Touch* touch, cocos2d::Event* event);
        ...
};

请注意,您需要listener->onTouchBegan CC_CALLBACK_X重定向到bool功能。如果这个函数返回true,那么onTouchEnd函数就可以正常工作,当这个函数返回false时就没有了。

希望它有所帮助。