Navigation

Part 5 - Text Input

To allow the player to be able to type their name in, we need to listen for one more event:

this.input.keyboard.on('keyup', this.anyKey, this);

This is a generic 'any key' event. When invoked, it calls this function:

anyKey (event)
{
    //  Only allow A-Z . and -

    let code = event.keyCode;

    if (code === Phaser.Input.Keyboard.KeyCodes.PERIOD)
    {
        this.cursor.set(6, 2);
        this.pressKey();
    }
    else if (code === Phaser.Input.Keyboard.KeyCodes.MINUS)
    {
        this.cursor.set(7, 2);
        this.pressKey();
    }
    else if (code === Phaser.Input.Keyboard.KeyCodes.BACKSPACE || code === Phaser.Input.Keyboard.KeyCodes.DELETE)
    {
        this.cursor.set(8, 2);
        this.pressKey();
    }
    else if (code >= Phaser.Input.Keyboard.KeyCodes.A && code <= Phaser.Input.Keyboard.KeyCodes.Z)
    {
        code -= 65;

        let y = Math.floor(code / 10);
        let x = code - (y * 10);

        this.cursor.set(x, y);
        this.pressKey();
    }
}

Here we first check the key code is valid. If it is, we set the cursor to be over the relevant area of the character chart. So, for the period, we put the cursor at 6x2, the location of the period character. If they press either the backspace or delete key, we'll position the cursor on the 'RUB' character.

If they press any of the keys A to Z, a little math is used to work out the character position.

Finally, we invoke the pressKey function. Because this function works by using the cursor coordinates, it doesn't matter how those were set: From a mouse click, from using the cursors to move around, or just by typing directly. All it cares is that the cursor values are current. One function to rule them all, as it were.

If we now run this code we've got a fully-fledged entry system, with all bases covered:

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

Finally, let's add a few special effects.