Search code examples
windowsmacoscocos2d-xkeyboard-eventscocos2d-x-3.0

Cococs2d-x keyboard implementation


I'm using cocos2d-x to make a game for windows, mac, and linux I want to use keyboard in my game but there is no official keyboard implementation in cocos2d-x3.0alpha. I read a lot of forum posts about keyboard implementation and I've seen some customized cocos2d-x braches but I already modified my cocos2d-x so I need the code to place in CCDirector or other classes. Can someone give me the code on how to get this working? (not a project I would like code that will work on all of the above platforms)
Thanks!


Solution

  • So I got it working I also made a tutorial which you can check here: http://www.cocos2d-x.org/forums/6/topics/39145

    We will start by making two functions in the scene we want keyboard on. They will be:

    OurScene.h:

    void keyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event);
    void keyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event);
    

    OurScene.cpp:

    void OurScene::keyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event)
    {
    
    }
    void OurScene::keyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event)
    {
    
    }
    

    These functions will be called when we press/release a key on the keyboard. Next we need a listener to look for the keyboard we will create it like so (I did it in the init function)

    auto keyboardListener = EventListenerKeyboard::create();
    keyboardListener->onKeyPressed = CC_CALLBACK_2(OurScene::keyPressed, this);
    keyboardListener->onKeyReleased = CC_CALLBACK_2(OurScene::keyReleased, this);
    EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(keyboardListener, this); // use if your version is below cocos2d-x 3.0alpha.1
    // use this: Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyboardListener, this); if you are using cocos2d-x 3.0alpha.1 and later!
    

    This code creates a keyboard listener and then setting what functions will be called when the key is pressed or released. Now Our program can detect keyboard!

    Wait… How do I know what key is pressed? It is simple! Let me show you:

    //put this inside keyPressed or keyReleased
    if (keyCode == EventKeyboard::KeyCode::KEY_W)
    {
        CCLog("W key was pressed");
    }
    

    This piece of code will check what is the key-code of the key that was pressed. The list of key-codes is inside the EventKeyboard class. To use a keycode you just type: EventKeyboard::KeyCode::KEY_**whatever key** - you will usually get a list of available keys to chose from.