Handling keyboard input in cocos2d-html5

Using keyboard input in Cocos2d-html5 applications is very simple. All that needs to be done is enabling the keyboard input in the layer that should receive the input. This is done by calling the setKeyboardEnabled method inside the layer:

layerThatshouldReveiceTheKeyboardInput.setKeyboardEnabled(true);

Now the information of which key has been pressed or released can be retrieved using these functions: onKeyDown and onKeyUp. When you add these functions to your level object they will be called each time a key is pressed or released. Both these functions have a pressed key type as function parameter, so you can easily determine which key was pressed by the user.

Here is a sample class that receives keyboard input:

classes.layers.Level = cc.Layer.extend({

    ctor : function() {
        this._super();
        this.setKeyboardEnabled(true);
        this.keyboardArrows = {
            left : false,
            right : false,
            up : false,
            down : false
        }
    },

    onKeyDown : function(key) {
        switch (key) {
        case 37:
            this.keyboardArrows.left = true;
            break;
        case 38:
            this.keyboardArrows.up = true;
            break;
        case 39:
            this.keyboardArrows.right = true;
            break;
        case 40:
            this.keyboardArrows.down = true;
            break;
        }
    },

    onKeyUp : function(key) {
        switch (key) {
        case 37:
            this.keyboardArrows.left = false;
            break;
        case 38:
            this.keyboardArrows.up = false;
            break;
        case 39:
            this.keyboardArrows.right = false;
            break;
        case 40:
            this.keyboardArrows.down = false;
            break;
        }
    }
});