直播软件 app 开发助力企业在竞争中脱颖而出的关键策略
1008
2022-10-09
Cocos2d-x之KeyboardEvent键盘事件
在游戏所在目录的Classes目录下创建以下两个文件:KeyboardScene.h:
#include "cocos2d.h"class KeyboardScene : public cocos2d::Layer{public: static cocos2d::Scene* createScene(); virtual bool init(); CREATE_FUNC(KeyboardScene);};
KeyboardScene.cpp:
//// Created by kyun on 20-3-19.//#include "KeyboardScene.h"USING_NS_CC;Scene* KeyboardScene::createScene() { auto scene = Scene::create(); auto layer = KeyboardScene::create(); scene->addChild(layer); return scene;}bool KeyboardScene::init() { if( !Layer::init()){ return false; } // 创建一个精灵 auto sprite = Sprite::create("HelloWorld.png"); // 将精灵定位到场景中央 sprite->setPosition(this->getContentSize().width/2,this->getContentSize().height/2); this->addChild(sprite,0); // 创建键盘- auto eventListener = EventListenerKeyboard::create(); // 定义键盘按下处理函数 eventListener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event){ Vec2 loc = event->getCurrentTarget()->getPosition(); switch (keyCode){ // 按下向左箭头,或A键 case EventKeyboard::KeyCode ::KEY_LEFT_ARROW: case EventKeyboard::KeyCode ::KEY_A: // 将与事件绑定的精灵向左移,按一下,移一下 event->getCurrentTarget()->setPosition(--loc.x,loc.y); break; // 按下向右箭头,或D键 case EventKeyboard::KeyCode ::KEY_RIGHT_ARROW: case EventKeyboard::KeyCode ::KEY_D: // 将与事件绑定的精灵向右移,按一下,移一下 event->getCurrentTarget()->setPosition(++loc.x,loc.y); break; // 按下向上箭头,或W键 case EventKeyboard::KeyCode ::KEY_UP_ARROW: case EventKeyboard::KeyCode ::KEY_W: // 将与事件绑定的精灵向上移,按一下,移一下 event->getCurrentTarget()->setPosition(loc.x,++loc.y); break; // 按下向下箭头,或S键 case EventKeyboard::KeyCode ::KEY_DOWN_ARROW: case EventKeyboard::KeyCode ::KEY_S: // 将与事件绑定的精灵向下移,按一下,移一下 event->getCurrentTarget()->setPosition(loc.x,--loc.y); break; } }; // 将事件-与精灵进行绑定 this->_eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener,sprite);}
修改根目录下的CMakeLists.txt文件:
# add cross-platforms source files and header files list(APPEND GAME_SOURCE Classes/AppDelegate.cpp Classes/KeyboardScene.cpp )list(APPEND GAME_HEADER Classes/AppDelegate.h Classes/KeyboardScene.h )
执行cmake命令:
~/Desktop/Games/MyGame/build/linux-build$ cmake ../..
编译源码:
~/Desktop/Games/MyGame/build/linux-build$ make -j 4
运行游戏:
~/Desktop/Games/MyGame/build/linux-build$ cd bin/MyGame~/Desktop/Games/MyGame/build/linux-build/bin/MyGame$ ./MyGame
测试:
通过键盘WASD四个键或四个方向键来移动精灵。
谢谢阅读!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~