zoukankan      html  css  js  c++  java
  • Cocos2d-JS键盘事件

    Cocos2d-JS中的键盘事件与触摸事件不同,它没有空间方面信息。键盘事件不仅可以响应键盘,还可以响应设备的菜单。
    键盘事件是EventKeyboard,对应的键盘事件监听器(cc.EventListener.KEYBOARD),键盘事件响应属性:
    onKeyPressed。当键按下时回调该属性所指定函数。
    onKeyReleased。当键抬起时回调该属性所指定函数。
    使用键盘事件处理的代码片段如下:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. onEnter: function () {  
    2.         this._super();  
    3.         cc.log("HelloWorld onEnter");  
    4.       
    5.         cc.eventManager.addListener({   ①  
    6.         event: cc.EventListener.KEYBOARD,   ②  
    7.         onKeyPressed:  function(keyCode, event){    ③  
    8.         cc.log("Key with keycode " + keyCode + " pressed");  
    9.         },  
    10.         onKeyReleased: function(keyCode, event){    ④  
    11.         cc.log("Key with keycode " + keyCode + " released");  
    12.         }  
    13.         }, this);  
    14.     },  
    15.     onExit: function () {  
    16.         this._super();  
    17.         cc.log("HelloWorld onExit");  
    18.         cc.eventManager.removeListeners(cc.EventListener.KEYBOARD); ⑤  
    19.     }  

    上述代码第①行cc.eventManager.addListener是通过快捷方式注册事件监听器对象。第②行代码是设置键盘事件cc.EventListener.KEYBOARD。第③行代码是设置键盘按下属性onKeyPressed,其中的参数keyCode是按下的键编号。第④行代码是设置键盘抬起属性onKeyReleased。
    上述onExit()函数是退出层时候回调,我们在代码第⑤行注销所有键盘事件的监听。
    我们可以使用Cocos Code IDE和WebStorm工具进行测试,输出的结果如下:

    [html] view plaincopy在CODE上查看代码片派生到我的代码片
     
    1. JS: Key with keycode 124 released  
    2. JS: Key with keycode 124 pressed  
    3. JS: Key with keycode 139 pressed  
    4. JS: Key with keycode 139 released  
    5. JS: Key with keycode 124 released  
    6. JS: Key with keycode 139 pressed  
    7. JS: Key with keycode 124 pressed  
    8. JS: Key with keycode 139 released  
    9. JS: Key with keycode 124 released  
    10. JS: Key with keycode 139 pressed  
    11. JS: Key with keycode 124 pressed  
    12. JS: Key with keycode 139 released  
    13. JS: Key with keycode 124 released  
    更多内容请关注最新Cocos图书《Cocos2d-x实战:JS卷——Cocos2d-JS开发》

    本书交流讨论网站:http://www.cocoagame.net

    欢迎加入Cocos2d-x技术讨论群:257760386

    更多精彩视频课程请关注智捷课堂Cocos课程:http://v.51work6.com

    《Cocos2d-x实战 JS卷》现已上线,各大商店均已开售:

    京东:http://item.jd.com/11659698.html

    欢迎关注智捷iOS课堂微信公共平台,了解最新技术文章、图书、教程信息

  • 相关阅读:
    交换机工作原理
    MyBatis框架的使用及源码分析(一) 配置与使用
    MySQL5.6安装步骤
    mysql创建用户,并授权
    命令行访问远程mysql数据库
    [mybatis] mybatis错误:Invalid bound statement (not found)
    【大数据】每秒十万笔交易的数据架构解读
    【mybaits】Mybatis中模糊查询的各种写法
    【redis】 linux 下redis 集群环境搭建
    [linux] linux下编译安装zlib
  • 原文地址:https://www.cnblogs.com/iOS-Blog/p/4384707.html
Copyright © 2011-2022 走看看