O'Reilly logo

Building HTML5 Games with ImpactJS by Jesse Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Key Binding

Impact has an easy-to-use input class, ideal for capturing keyboard input, which can be found in the ig.input namespace. To capture keyboard events, we will need to bind the key press event to the desired key in the input class. Let’s put the following code at the beginning of the init() function in main.js, just above our load level code:

// Bind keys
ig.input.bind( ig.KEY.LEFT_ARROW, 'left' );
ig.input.bind( ig.KEY.RIGHT_ARROW, 'right' );
ig.input.bind( ig.KEY.X, 'jump' );
ig.input.bind( ig.KEY.C, 'shoot' );

For our game, we are going to track the left and right arrows along with the X and C keys. This is the first step in setting up controls for your game. In a little while, we’ll set up code to react to the left, right, jump and shoot commands those keys will trigger.

There is a list of constants that contains all the keys Impact can use in the ig.KEY class. To use them, simply apply a custom label to a key so that when we poll for input during game play, we will be able to react to the desired event when each key is pressed.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required