Character, Movement and Input on a Tile Map

The Character Class

In this lesson, we'll expand on our project to include a character which we can move about. This will involve creating a character object, listening and storing keypresses for the arrow keys, adding movement processing, and drawing the character.

We'll start by adding a map of keyCodes to boolean flags to tell us which of the arrow keys are currently pressed. The keyCodes 37 to 40 represent the arrow keys Left, Up, Right, and Down, in that order. To begin with, we'll assume that none of these keys are pressed and set all the flags to false.

var keysDown = {
37 : false,
38 : false,
39 : false,
40 : false
};

We'll also add another global variable - player, which will store an instance of the new Character object which we'll create in a moment. In Javascript, we can initialize variables before the class has been defined in the code; whilst not good practice, it'll work fine in this situation as we're doing everything in a single file.

var player = new Character();

The Character class and its methods

We'll now create a Character class. This will store information about the player we create, and allow us to modify it through the methods we'll create in a moment. We're doing this as a class instead of creating a single Javascript object so that we can add more Characters later on.

The Character class will store the coordinates of the tiles the Character is currently moving from and to (tileFrom, tileTo), the time (in milliseconds) at which the Character began to move (timeMoved), the dimensions of the Character in pixels (dimensions), the true position of the Character on the Canvas in pixels (position), and the time (in milliseconds) it will take the Character to move 1 tile (delayMove).

We're going to give out Character a placeAt method, which will allow us to place it directly on the tile we specify. This will help with initially placing the character, and resetting movement related properties to the new tile.

Our function takes two arguments; the x and y position of the destination tile. It then updates the tileFrom and tileTo properties to the new tile coordinates, and calculates the pixel position of the character using the following method:

In simple terms, the horizontal and vertical positions of the character are the same offsets at which the tile is drawn, adding half the difference between the character width (or height) and the tile width (or height).