#include "HelloWorldScene.h" #include "cocostudio/CocoStudio.h" #include "ui/CocosGUI.h" USING_NS_CC; using namespace cocostudio::timeline; Scene* HelloWorld::createScene() { auto scene = Scene::create(); auto layer = HelloWorld::create(); scene->addChild(layer); return scene; } bool HelloWorld::init() { if ( !Layer::init() ) { return false; } //获取屏幕尺寸 Size visibleSize = Director::getInstance()->getVisibleSize(); //获取坐标原点 Vec2 origin = Director::getInstance()->getVisibleOrigin(); //加载鼠标图标精灵 Sprite *mouse = Sprite::create("mouse.png"); mouse->setScale(0.5f); this->addChild(mouse); //创建事件监听器,监听键盘事件 auto myKeyListener = EventListenerKeyboard::create(); //当键盘被按下时响应 myKeyListener->onKeyPressed = [](EventKeyboard::KeyCode keycode, cocos2d::Event *event) { CCLOG("key is pressed,keycode is %d", keycode); }; //当键盘按键弹回时响应 myKeyListener->onKeyReleased = [](EventKeyboard::KeyCode keycode, cocos2d::Event *event) { CCLOG("key is released,keycode is %d", keycode); }; //创建事件监听器,监听鼠标事件 auto myMouseListener = EventListenerMouse::create(); //鼠标移动 myMouseListener->onMouseMove = [=](Event *event) { EventMouse *e = (EventMouse*)event; mouse->setPosition(e->getCursorX(), e->getCursorY()); }; //当鼠标被按下 myMouseListener->onMouseDown = [=](Event *event) { mouse->setScale(0.2f); }; //当鼠标弹起 myMouseListener->onMouseUp = [=](Event *event) { mouse->setScale(0.5f); }; //将事件监听器与场景绑定 _eventDispatcher->addEventListenerWithSceneGraphPriority(myKeyListener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(myMouseListener, this); return true; }
运行结果,可以看到鼠标图标跟着鼠标的位置移动
点击一下后,发现鼠标缩小了,这是可以自己在代码里调试的
在VS输出栏也可以看到如下图所示
知识点积累:
cursor光标 pressed按下 released释放 origin原点
事件监听器有以下几种:
- 触摸事件 (EventListenerTouch)
- 键盘响应事件 (EventListenerKeyboard)
- 鼠标响应事件 (EventListenerMouse)
- 自定义事件 (EventListenerCustom)
- 加速记录事件 (EventListenerAcceleration)
_eventDispatcher
的工作由三部分组成:
- 事件分发器 EventDispatcher
- 事件类型 EventTouch, EventKeyboard 等
- 事件监听器 EventListenerTouch, EventListenerKeyboard 等
注册的时候有两种方法,一种是addEventListenerWithSceneGraphPriority
,另一种是addEventListenerWithFixedPriority
,其中addEventListenerWithSceneGraphPriority
会自动释放,所以可以优先使用这种方法。