Marek Krzeminski
Marek Krzeminski

Reputation: 1398

How to make a tooltip appear when hovering mouse over a Phaser.GameObject.Image?

In my Phaser 3 game I'm using Phaser.GameObjects.Image 's as things that a user can click on. When a user's mouse hovers over an image I would like a tooltip with text to fade in and appear. When the mouse moves off the image, I'd like the tooltip to disappear.

How can I implement this behavior in Phaser? I'm new to Phaser and I don't see a ToolTip class in the framework.

Upvotes: 1

Views: 1349

Answers (1)

winner_joiner
winner_joiner

Reputation: 14925

You could:

  • use the pointer events for detecting, that the pointer is over an object
  • and animate/tween the alpha property on the over event
    • you can alter the speed with the tween duration
  • and hide the toolTip on the out event

Here the docs to the Input events: https://photonstorm.github.io/phaser3-docs/Phaser.Input.Events.html

Here a mini example:

var config = {
    type: Phaser.WEBGL,
    parent: 'phaser-example',
    width: 800,
    height: 600,
    scene: {
        create: create
    }
};

var game = new Phaser.Game(config);
var toolTip; 
var toolTipText;

function create ()
{
    let objectWithToolTip = this.add.rectangle( 100, 100, 100, 100, 0xffffff).setInteractive();

    toolTip =  this.add.rectangle( 0, 0, 250, 50, 0xff0000).setOrigin(0);
    toolTipText = this.add.text( 0, 0, 'This is a white rectangle', { fontFamily: 'Arial', color: '#000' }).setOrigin(0);
    toolTip.alpha = 0;
 
    this.input.setPollOnMove();
    this.input.on('gameobjectover', function (pointer, gameObject) {
        this.tweens.add({
          targets: [toolTip, toolTipText],
          alpha: {from:0, to:1},
          repeat: 0,
          duration: 500
      });
    }, this);

    this.input.on('gameobjectout', function (pointer, gameObject) {
        toolTip.alpha = 0;
        toolTipText.alpha = 0;
    });
    
    objectWithToolTip.on('pointermove', function (pointer) {
        toolTip.x = pointer.x;
        toolTip.y = pointer.y;
        toolTipText.x = pointer.x + 5;
        toolTipText.y = pointer.y + 5;
    });

}
<script src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js"></script>

Info: if you want to dig deeper into the phaser events you can checkout some examples on the offical home page: https://phaser.io/examples/v3/category/input/mouse are really good, and explore may use cases.

Extra Info: If you don't want to re-invent the wheel, there are several plugins, that can be loaded into phaser(that add special functionality to phaser).
It is always good to check this page(https://phaserplugins.com/), before implementing so common feature/function. There is even on specially for tooltips https://github.com/netgfx/Phaser-tooltip

Upvotes: 3

Related Questions