Hello everyone! For a week I’ve been looking on how to make a keyboard work!
I managed to figure it out and I want to share my knowledge with you!
So,before we get started - this tutorial only works on Cocos2d-x 3.0alpha and later.
We will start by making two functions in the scene we want keyboard on.
They will be:@H_403_5@
首先在需要键盘处理事件的场景中文件中添加如下两个函数。@H_403_5@
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)@H_403_5@
接下来在init()方法中添加如下代码来监听键盘事件。@H_403_5@
auto keyboardListener = EventListenerKeyboard::create(); keyboardListener->onKeyPressed = CC_CALLBACK_2(OurScene::keyPressed,this); keyboardListener->onKeyReleased = CC_CALLBACK_2(OurScene::keyReleased,this); EventDispatcher::getInstance()->addEventListenerWithSceneGraPHPriority(listener,this); // use if your version is below cocos2d-x 3.0alpha.1 // use this: Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraPHPriority(listener,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:@H_403_5@
然后就可以在最上面的两个方法中添加keyCode的判定了。@H_403_5@
//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.@H_403_5@
Well,I think that’s it! Enjoy!@H_403_5@