Skip to content

Phaser: Keyboard events

New Course Coming Soon:

Get Really Good at Git

This post is part of a Phaser series. Click here to see the first post of the series.

Mouse events are fired on a GameObject, because with the mouse we click on elements.

With the keyboard instead we press keys, not linked to any GameObject in particular.

So we listen for those events on this.input.keyboard, like this:

this.input.keyboard.on(<event>, function() {

})

<event> is a string that can be keyup or keydown, to intercept all keys pressed, or a combination of it with a letter identifying a specific key, like:

We have a large number of identifiers we can use, including:

Instead of listenining on individual keys, we can get an object calling this.input.keyboard.createCursorKeys():

let cursors

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

and in the update() function, we can check if one specific key has been pressed, and do something when this happens:

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
  }
}
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!

Here is how can I help you: