Cocos2d-JS中的键盘事件与触摸事件不同,它没有空间方面信息。键盘事件不仅可以响应键盘,还可以响应设备的菜单。
键盘事件是EventKeyboard,对应的键盘事件监听器(cc.EventListener.KEYBOARD),键盘事件响应属性:
onKeyPressed。当键按下时回调该属性所指定函数。
onKeyReleased。当键抬起时回调该属性所指定函数。
使用键盘事件处理的代码片段如下:onEnter: function () {
this._super();
cc.log(HelloWorld onEnter);
cc.eventManager.addListener({ ①
event: cc.EventListener.KEYBOARD,②
onKeyPressed:function(keyCode, event){③
cc.log(Key with keycode+ keyCode +pressed);
},
onKeyReleased: function(keyCode, event){④
cc.log(Key with keycode+ keyCode +released);
}
}, this);
},
onExit: function () {
this._super();
cc.log(HelloWorld onExit);
cc.eventManager.removeListeners(cc.EventListener.KEYBOARD); ⑤
}
上述代码第①行cc.eventManager.addListener是通过快捷方式注册事件监听器对象。第②行代码是设置键盘事件cc.EventListener.KEYBOARD。第③行代码是设置键盘按下属性onKeyPressed,其中的参数keyCode是按下的键编号。第④行代码是设置键盘抬起属性onKeyReleased。
上述onExit()函数是退出层时候回调,我们在代码第⑤行注销所有键盘事件的监听。
我们可以使用Cocos Code IDE和WebStorm工具进行测试,输出的结果如下:JS: Key with keycode 124 released
JS: Key with keycode 124 pressed
JS: Key with keycode 139 pressed
JS: Key with keycode 139 released
JS: Key with keycode 124 released
JS: Key with keycode 139 pressed
JS: Key with keycode 124 pressed
JS: Key with keycode 139 released
JS: Key with keycode 124 released
JS: Key with keycode 139 pressed
JS: Key with keycode 124 pressed
JS: Key with keycode 139 released
JS: Key with keycode 124 released