Cocos2d-JS鍵盤事件
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 releasedJS: Key with keycode 124 pressedJS: Key with keycode 139 pressedJS: Key with keycode 139 releasedJS: Key with keycode 124 releasedJS: Key with keycode 139 pressedJS: Key with keycode 124 pressedJS: Key with keycode 139 releasedJS: Key with keycode 124 releasedJS: Key with keycode 139 pressedJS: Key with keycode 124 pressedJS: Key with keycode 139 releasedJS: Key with keycode 124 released