Cocos2d-x 3.1以降でのAndroidバックキーのKeyCodeはKEY_ESCAPEに

KEY_BACKSPACEからKEY_ESCAPEに

Cocos2d-x 3.3でAndroidのバックキーイベント取得がうまく取れなかったのでメモ。

バックキーのイベント取得についてググるとKeyCodeが「KEY_BACKSPACE」で取得できるという情報が出てくるが、バージョン3.1以降は「KEY_ESCAPE」に変わった模様。

Because desktop and mobile phones share the same key code, and escape is used as back menu on desktop.

fix keycode_back  from  KEY_ESCAPE to  KEY_BACKSPACE by joshuastray · Pull Request #6853 · cocos2d/cocos2d-x · GitHub

実際にバックキーのイベントを取得する際は、以下3箇所の記述が必要。

ヘッダーファイルにonKeyReleasedを定義
public:
    void onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event);
.cppファイルのinit()にイベントリスナーを追加
bool HogeScene::init()
{
    if ( !Layer::init() )
    {
         return false;
    }

    auto keyboardListener = cocos2d::EventListenerKeyboard::create();
    keyboardListener->onKeyReleased = CC_CALLBACK_2(HogeScene::onKeyReleased, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
onKeyReleased()でバックキーのイベントを取得
void HogeScene::onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event * event)
{
    if (keyCode == EventKeyboard::KeyCode::KEY_ESCAPE)
    {
        Director::getInstance()->end(); // アプリを終了させる
    }
}

ここではKeyCodeを「KEY_ESCAPE」としているが「KEY_BACK」でも同じ扱いらしい。

参考

星影

Tech Hunter代表。マルチポテンシャライト。 ガジェット、アニメ、ゲーム、インターネットが好き。

関連記事

特集記事

コメント

この記事へのコメントはありません。

TOP