FrozenJS Input Example

Simple demo that shows how to handle keyboard input.

by monteslu

HTML

<script src="http://rawgithub.com/iceddev/frozen/master/dist/frozen.js.uncompressed.js"></script>
<div id="gameArea">
    <canvas id="canvas" width="300" height="400"></canvas>
</div>

CSS

body {
    background-color: #222;
    color: #fff;
}
#gameArea {
    margin: 0 auto;
}

JavaScript

require(['frozen/GameCore', 'dojo/keys'], function (GameCore, keys) {
    var x = 50;
    var y = 50;
    var speed = 3;

    var game = new GameCore({
        canvasId: 'canvas',
        gameAreaId: 'gameArea',
        canvasPercentage: 1,
        initInput: function (im) { // im = this.inputManager
            //tells the input manager to listen for key events
            im.addKeyAction(keys.LEFT_ARROW);
            im.addKeyAction(keys.RIGHT_ARROW);
            im.addKeyAction(keys.UP_ARROW);
            im.addKeyAction(keys.DOWN_ARROW);
        },
        handleInput: function (im) {
            //just an example showing how to check for presses, could be done more effeciently
            if (im.keyActions[keys.LEFT_ARROW].isPressed()) {
                x-= speed;
            }
            if (im.keyActions[keys.RIGHT_ARROW].isPressed()) {
                x+= speed;
            }
            if (im.keyActions[keys.UP_ARROW].isPressed()) {
                y-= speed;
            }
            if (im.keyActions[keys.DOWN_ARROW].isPressed()) {
                y+= speed;
            }
        },
        draw: function (ctx) {
            ctx.fillRect(0, 0, this.width, this.height);
            ctx.fillStyle = 'white';
            ctx.fillRect(x, y, 50, 50);
        }
    });

    game.run();
});