/

Phaser: Keyboard Events

Phaser: Keyboard Events

This blog post is part of a series on Phaser. If you haven’t read the first post yet, you can find it here.

Unlike mouse events, which are fired on a GameObject, keyboard events are not directly linked to any specific GameObject. Instead, we listen for keyboard events on the this.input.keyboard object.

To listen for keyboard events, we can use the following syntax:

1
2
3
this.input.keyboard.on(<event>, function() {
// event handler code
})

The <event> parameter is a string that can be either keydown or keyup, which allows us to intercept all keys being pressed or released. Additionally, we can combine the event type with a specific key identifier, such as:

  • keyup-A
  • keyup-THREE
  • keydown-F12
  • keydown-ENTER

Phaser provides a wide range of key identifiers that we can use, including the letters A through Z, function keys F1 through F12, and common keys like BACKSPACE, TAB, ENTER, SHIFT, CTRL, ALT, and more.

In addition to listening for individual keys, we can also get an object that represents the arrow keys by calling this.input.keyboard.createCursorKeys():

1
2
3
4
5
let cursors;

function create() {
cursors = this.input.keyboard.createCursorKeys();
}

With this object, we can check if a specific arrow key has been pressed in the update() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function update() {
if (cursors.right.isDown) {
text.x += 5;
}
if (cursors.left.isDown) {
text.x -= 5;
}
if (cursors.up.isDown) {
text.y -= 5;
}
if (cursors.down.isDown) {
text.y += 5;
}
}

In this example, we are checking if the right arrow key is being pressed (cursors.right.isDown), and if so, we move the text object 5 units to the right (text.x += 5). Similarly, we handle the left, up, and down arrow keys.

tags: [“Phaser”, “Keyboard Events”, “Game Development”]