Tutorial 2: Moving the Square

In tutorial 1¬†we looked at code which outlined the game loop with it’s update and draw loops. We looked at the code which produced the rotating square.

In this tutorial we are going to explore the possibilities for moving the square. We are going to get the canvas element to accept keyboard input and then allow us to respond to this. The code can be found here. The demonstration can be found here.

Aim

The aim of this tutorial is to make a square (still rotating) which responds by moving when the user presses any of the ‘w’,’a’,’s’ or ‘d’ keys. These keys are the standard movement keys in most games so should seem familiar. By then end it should be fairly straightforward to assign whatever keys you like.

Accepting Keyboard Input

There is a problem with accepting keyboard input. We could simply move the square in the direction we want every time we get a “keydown” message. The problem with this is that you have to either keep pressing the button or you cannot press two buttons at the same time. The solution is to make a keyboard handler.

keyHandlerUtils.js

The key handler needs to be tied in to the loading section of our game. We do this by adding:

$(document).keydown(onKeyDown);
$(document).keyup(onKeyUp);

This sets up the key handler. The key handler tracks the onKeyDown messages and the onKeyUp. The reason for this is so that it can store the keyDowns in an array. It then removes them on the keyUps. The advantage of this is that we can simply make a call to another function “isKeyPressed()” and pass in a letter.

Changes to the update

Now we need to add the changes to location. If you look into the update of Square.js and you can see the correct usage of the isKeyPressed. That will demonstrate it’s usage better than I could explain with words.

Posted in Games, Ludum Dare

Leave a Reply