Canvas Basics - Moving the Square

In the first tutorial we looked about how to create a canvas and animate a square rotating on that canvas.

In this tutorial we shall be looking at how to interact with the square, using the keyboard. The code can be found here and an example of the working code can be found here.

Aim

The aim of this tutorial is to utilise the keys 'w', 'a', 's' and 'd' to move the rotating square from the first tutorial. By the end of the tutorial you will be able to reassign these keys as you choose.

Accepting Keyboard Input

We are able to write functions which are called when certain events happen. The events we have access to are onKeyDown and onKeyUp. These events occur, as you might expect, when a key is pressed and also when it is released. The problem is that we need a way of tracking when a key is held down - otherwise we would have to repeatedly hit the key to move the square (a frustrating mechanic for any game!). The solution is to create a key handler.

keyHandlerUtils.js

The key handler is all ready to but needs to be tied into our game. We do that by adding the following code into the initiation
$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);
This sets up the key handler. Now this is set up we can simply call the global isKeyPressed() function and pass a letter name in as an argument, for instance
isKeyPressed('w')
This will return either true or false. So then in the update for the Square class we can see that the following code will control the movement
function sqUpdate(){
// Check the keys that are down
if(isKeyPressed('A')){
this.loc.x-=1;
}
...
}
This way the location of the square will move by 1 everytime the update loop is run (see information on the game loop from the first tutorial for more information).