Can't get touch to work in multi-platform cocos2d-x app

▼魔方 西西 提交于 2019-12-03 02:58:20

Currently, cocos2dx is going through a major overhauling of the library and many things have changed including Touch registration and propagation. Here is how it works now:

GameLayer.h

class GameLayer : public cocos2d::Layer
{
public:
    static cocos2d::Layer* createLayer();
    void update(float dt);
    virtual bool init();
    CREATE_FUNC(GameLayer);

private:
    virtual void onEnter();
    virtual void onExit();

    bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event);
    void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event);
    void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event);
};

GameLayer.cpp

cocos2d::Layer* GameLayer::createLayer()
{
    GameLayer *layer = GameLayer::create();

    return layer;
}

bool GameLayer::init()
{
    if (!cocos2d::Layer::init())
    {
        return false;
    }

    this->schedule(schedule_selector(GameLayer::update));

    return true;
}

void GameLayer::onEnter()
{
    Layer::onEnter();

    // Register Touch Event
    auto dispatcher = Director::getInstance()->getEventDispatcher();
    auto listener = EventListenerTouchOneByOne::create();

    listener->onTouchBegan = CC_CALLBACK_2(GameLayer::onTouchBegan, this);
    listener->onTouchMoved = CC_CALLBACK_2(GameLayer::onTouchMoved, this);
    listener->onTouchEnded = CC_CALLBACK_2(GameLayer::onTouchEnded, this);

    dispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}

void GameLayer::onExit()
{
    // You don't need to unregister listeners here as new API
    // removes all linked listeners automatically in CCNode's destructor
    // which is the base class for all cocos2d DRAWING classes

    Layer::onExit();
}

void GameLayer::update(float dt)
{

}

bool GameLayer::onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event)
{
    cocos2d::log("You touched %f, %f", touch->getLocationInView().x, touch->getLocationInView().y);
    return true;
}

void GameLayer::onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event)
{

}

void GameLayer::onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event)
{

}

Hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!