Cocos2d-JS Keyboard Events
Keyboard Events in the Cocos2d-JS are different from touch events, and it has no spatial information. Keyboard Events not only respond to the keyboard, but also to the menu of the device.
The KEYBOARD event is EventKeyboard, the corresponding KEYBOARD event listener (cc. EventListener. KEYBOARD), and the KEYBOARD Event Response attributes:
OnKeyPressed. When the key is pressed, the function specified by this attribute is called back.
OnKeyReleased. When the key is lifted, the function specified by this attribute is called back.
The code snippet for handling Keyboard Events is as follows:
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);⑤ }
Line ① Of the above Code cc. eventManager. addListener is used to register the event listener object through shortcuts. The Code in line ② sets the KEYBOARD event cc. EventListener. KEYBOARD. The Code in line ③ sets the keyboard to press the attribute onKeyPressed, And the keyCode parameter is the key number that is pressed. The fourth line of code is to set the keyboard to lift the attribute onKeyReleased.
The above onExit () function is called back when the exit layer is used. In line 5 of the Code, we deregister the listening of all Keyboard Events.
We can use Cocos Code IDE and WebStorm tools for testing. The output result is as follows:
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