Phaser: Mouse input

By

Learn how to handle mouse input in Phaser by making a GameObject interactive with setInteractive, then listening for events like pointerup with on.

~~~

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

To handle mouse input in Phaser, you first make a GameObject interactive with setInteractive(), then you listen for pointer events on it with on().

Any GameObject can be made interactive: text, sprites, images.

Here’s how we make a text object interactive:

text = this.add.text(100, 100, 'test')
text.setInteractive()

Once a GameObject is interactive, it can listen for events.

This is done using the on() method. We pass an event name, and a callback function that’s executed when the event occurs:

text.on('pointerup', function () {})

pointerup is just one of the mouse events we can listen for. We also have:

Phaser calls them pointer events because they cover both mouse and touch input. The same code works on desktop and on a phone.

Getting the pointer position

The callback receives a pointer object. Its x and y properties tell you where the click happened:

text.on('pointerdown', (pointer) => {
  console.log(pointer.x, pointer.y)
})

Reacting to hover

pointerover and pointerout are the events you use for hover effects. Here we highlight the text when the mouse enters it, and restore it when it leaves:

text.on('pointerover', () => {
  text.setStyle({ fill: '#ff0' })
})

text.on('pointerout', () => {
  text.setStyle({ fill: '#fff' })
})

Scene-level events

gameobjectdown is a more general event that is fired when any interactive element is clicked, and it’s not fired on an object, but on this.input:

this.input.on('gameobjectdown', (pointer, gameObject) => {
  console.log(gameObject)
})

The callback gets the pointer and the GameObject that was clicked. This is handy when you have many clickable objects and want one handler for all of them.

You can also listen for clicks anywhere in the game, not just on objects:

this.input.on('pointerdown', (pointer) => {
  console.log(pointer.x, pointer.y)
})

A common mistake

If your click handlers never fire, check you called setInteractive() on the object. Phaser does not raise an error when you attach a pointer listener to a non-interactive object. The callback just never runs, which makes this easy to miss.

This is just the beginning. We have many advanced mouse (and touch) controls at our disposal, like drag events and custom hit areas.

Tagged: Phaser · All topics
~~~

Related posts about phaser: