Easy display of mouse XY location in Phaser 3 canvas?

My game uses a 2D image as a background. I am using other in-game objects to create the illusion of interaction with the 2D background image. For example, I overlay a simple rectangle over the stairs and then set it’s alpha to 0 and angle it to properly match the angle of the stairs. This creates the illusion of sliding up the stairs when in reality the player is sliding up an invisible angled rectangle, with the player and rectangle physics being managed by MatterJS.

Because of this, I need to accurately locate various X, Y coordinates on the background image, and in a scale independent manner (i.e. - same X, Y point regardless of the user’s zoom factor with the browser tab hosting the Phaser 3 canvas).

Is there a little bit of code that I could add to my game for dev purposes only, that would display the current coordinates of the mouse and show the exact XY coordinate it is hovering over, with the coordinates being relative to the Phaser 3 canvas? Note, if you have a simpler or better way to do this please let me know. Otherwise I’ll be spending a lot of time “pixel location tweaking” to get things to look right.

gameScene.create = function() {
    this.label = this.add.text(0, 0, '(x, y)', { fontFamily: '"Monospace"'});
    this.pointer = this.input.activePointer;
}

gameScene.update = function() {
    this.label.setText('(' + this.pointer.x + ', ' + this.pointer.y + ')');
}

This should work to put a little coordinate in the upper-left corner that will always display where your mouse is relative to the game display area. It works scale-independent with the upper-left corner always being 0,0 and the bottom-right being the max size of the game canvas. If you scale it up, you can get some decimals in the numbers, but the numbers are still the same. You can just cut off the decimals and be fine.

EDIT: Actually, just add Math.round() on the pointers in the setText and then you don’t have to worry about getting decimals.

1 Like