Cocos2d-x之KeyboardEvent键盘事件

网友投稿 613 2022-05-28

Cocos2d-x在ubuntu上的开发环境搭建,请参考《Ubuntu18.04搭建Cocos2d开发环境》

在Linux上运行项目,请参考《在Linux上运行Cocos2d-x项目》

在游戏所在目录的Classes目录下创建以下两个文件:

KeyboardScene.h:

#include "cocos2d.h" class KeyboardScene : public cocos2d::Layer{ public: static cocos2d::Scene* createScene(); virtual bool init(); CREATE_FUNC(KeyboardScene); };

1

2

3

4

5

6

7

8

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); }

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Cocos2d-x之KeyboardEvent键盘事件

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

修改根目录下的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 )

1

2

3

4

5

6

7

8

9

执行cmake命令

~/Desktop/Games/MyGame/build/linux-build$ cmake ../..

1

编译源码:

~/Desktop/Games/MyGame/build/linux-build$ make -j 4

1

运行游戏:

~/Desktop/Games/MyGame/build/linux-build$ cd bin/MyGame ~/Desktop/Games/MyGame/build/linux-build/bin/MyGame$ ./MyGame

1

2

测试:

通过键盘WASD四个键或四个方向键来移动精灵。

谢谢阅读!

Cocos2D

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:数字化时代下,为什么企业使用企业云盘在线办公如此重要?
下一篇:华为云服务器价格和收费方式
相关文章