Nanfeng

Notes on software development, code, and curious ideas

Handling Keyboard Input in Cocos2d-x with Lua

Cocos2d-x 3.17 exposes keyboard events to Lua through cc.EventListenerKeyboard. A listener needs callbacks for key presses and releases, and it must be attached to a node through the event dispatcher.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
local function addKeyboardListener(node)
local listener = cc.EventListenerKeyboard:create()

listener:registerScriptHandler(function(keyCode, event)
if keyCode == cc.KeyCode.KEY_ESCAPE then
print("Escape pressed")
elseif keyCode == cc.KeyCode.KEY_SPACE then
print("Space pressed")
end
end, cc.Handler.EVENT_KEYBOARD_PRESSED)

listener:registerScriptHandler(function(keyCode, event)
print("Key released:", keyCode)
end, cc.Handler.EVENT_KEYBOARD_RELEASED)

local dispatcher = node:getEventDispatcher()
dispatcher:addEventListenerWithSceneGraphPriority(listener, node)
return listener
end

Call it after the node has been created:

1
2
3
function GameScene:onEnter()
self.keyboardListener = addKeyboardListener(self)
end

Scene-graph priority associates the listener with the node, so it follows the node’s running state and is normally removed with it. If a listener was registered with fixed priority or needs early cleanup, remove it explicitly:

1
2
self:getEventDispatcher():removeEventListener(self.keyboardListener)
self.keyboardListener = nil

Keep platform differences in mind: desktop builds provide physical keyboard events, while mobile gameplay normally needs touch controls or a text-input component. Key-code names can also vary with the Cocos2d-x binding version, so check the constants generated for the project when a particular key is not recognized.

+