How to make graphics interactive

Just wondering how I go about making a simple graphics object interactive? The following doesn’t seem to work:

create ()
{
    this.graphics = this.add.graphics();
    this.graphics.setInteractive();
    this.graphics.fillStyle(0xffff00, 1);
    this.graphics.fillCircle(300, 300, 150);

    this.input.on('gameobjectdown',function (pointer, gameObject){
            gameObject.destroy();        
    }, this);
}

You can find examples here : Buttons in Phaser 3 - these buttons are simply interactive objects.

I think the event you listen to, 'gameobjectdown', is not valid.

From the linked page :

Great, we know our “button” is firing off input events that we can listen for and respond to. The other events that we care about are:

  • pointerout - this is the opposite of pointerover . It fires when the cursor leaves the area of the game object.
  • pointerdown - this fires at the start of a click or a touch on the game object, literally when the mouse button is pushed down or when a finger touches down.
  • pointerup - this is the opposite of pointerdown . It fires when the mouse button is released or a finger is lifted up from the game object.
1 Like

Thanks Olf. Those don’t seem to work with a graphics object.

create ()
    {
        this.graphics = this.add.graphics();
        this.graphics.setInteractive();
        this.graphics.fillStyle(0xffff00, 1);
        this.graphics.fillCircle(300, 300, 150);
        this.graphics.on('pointerdown', () => { console.log('pointerover'); });
    }

gameobjectdown can be used to listen to mouse click on game objects.

[edit] looks like I need to pass a shape and callback to setInteractive() for this to work. All good now :wink:

1 Like

Glad it’s working now. :tada:

From the quoted page :

These events are emitted in two ways:

  1. Directly from the GameObject itself
  2. From the InputPlugin object ( this.input in a scene)

It seems to me gameobjectdown is used with the second option, whereas here you are listening to events from a GameObject.

I’m know, I’m writing a lot about this subject but I’m learning at the same time. :wink:
Have a great time with Phaser 3.

Just to confirm: Graphics objects need to be passed a shape to use as the hit area for interaction.

If you’re just needing something simple like a circle or rectangle then use the Shape game objects as they support interaction directly.

3 Likes

Thanks @rich. I ended up using a graphics object and applying its texture to another object, which works fine. But shapes definitely look simpler. So much to learn.