
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:
首先在需要键盘处理事件的场景中文件中添加如下两个函数。
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)
当键盘按下时会调用上面这两的函数。
接下来在init()方法中添加如下代码来监听键盘事件。
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:
然后就可以在最上面的两个方法中添加keyCode的判定了。
//put this insIDe keypressed or keyreleasedif (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.
Well,I think that’s it! Enjoy!
总结以上是内存溢出为你收集整理的多平台响应键盘事件!(适用于Cocos2dx 3.0 alpha以上版本)全部内容,希望文章能够帮你解决多平台响应键盘事件!(适用于Cocos2dx 3.0 alpha以上版本)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)