Navigation

Part 4 - Keyboard Control

Published on 12th November 2018

To allow for keyboard input we're going to listen for the following keys:

this.input.keyboard.on('keyup_LEFT', this.moveLeft, this);
this.input.keyboard.on('keyup_RIGHT', this.moveRight, this);
this.input.keyboard.on('keyup_UP', this.moveUp, this);
this.input.keyboard.on('keyup_DOWN', this.moveDown, this);
this.input.keyboard.on('keyup_ENTER', this.pressKey, this);
this.input.keyboard.on('keyup_SPACE', this.pressKey, this);

The above code is added to the create function of the Input Panel class.

It should be pretty easy to follow. When the keyup event for the defined keys is hit, it will invoke the various handlers, such as moveLeft or pressKey.

Let's take a look at one of those functions:

moveLeft ()
{
    if (this.cursor.x > 0)
    {
        this.cursor.x--;
        this.block.x -= 52;
    }
    else
    {
        this.cursor.x = 9;
        this.block.x += 52 * 9;
    }
}

If they press the left cursor key then we move the cursor to the left. If the cursor was already on the x position of zero, then we wrap it around so it's now at the far-right of the highscore input table.

This same concept is used for all directions. If they press the Up cursor and they are on the top row, it'll wrap around to the bottom row, and so on.

Finally, we've hooked both the ENTER and the SPACE key to the pressKey function created earlier. This means that if they press either of those keys it will add the currently active letter to their name entry. We can use exactly the same function as the pointer up event uses.

Here's a demo of it running:

Note that in versions of Phaser before 3.16, when you move around the web page will probably scroll too.

This demo works well already. We can use the mouse, or cursors, to enter our name. But let's add one more method, too - the ability to just type it in.