Execute an arbitrary function based on key input(Phaser3)

This article can be read in about 3 minutes.
PR

やりたいこと

Execute an arbitrary function in Phaser3 upon key input.

Registration is done as follows:

this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A);

Within the update, you can execute arbitrary code by retrieving the following values from the above return value.

isDown

However, it’s best not to put key events other than those related to actions (e.g., pause and retry) inside the Update method.

PR

implement by on() function

This can be implemented on On, as follows.

It’s generally best to call it from Create.

The listener executes when the Space key is pressed.

        this.input.keyboard.on('keydown-SPACE', listener);

The SPACE part of keydown-SPACE can be replaced with any key. Changing it to keydown-A, for example, will make the listener execute when the ‘A’ key is pressed.

The listener is a function that takes an Event as an argument.

It’s also possible to write it as shown below without explicitly defining a function.

        this.input.keyboard.on('keydown-SPACE', event =>
        {
            //Process
        });
PR

Result

Key input can now be processed without the need for Update.

PR

Reference

Phaser 3 Examples

comment

Copied title and URL