Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouse events sent as inputs to phaser scene

Can you please show me how the dom can communicate mouse pointer movement events as an input to a phaser scene. I've seen how mouse movement can be tracked within the scene area; but once the mouse leaves and goes to other areas of the DOM, that data is not tracked. I figure if perhaps there was a way to have an input to communicate data from "the outside world" then this could be possible. I am very grateful for help and direction you could share.

like image 371
Benjamin McFerren Avatar asked Oct 11 '25 21:10

Benjamin McFerren


1 Answers

All you need to do is add an event listener to the DOM object you also want to track movement in using plain JavaScript. Then, you tie the event listener to the game method you want to execute when the event is triggered.

const body = document.querySelector('body');
body.onmousemove = (pointer) => {
  updatePoint(pointer);
};

And then setup your game as normal:

const config = {
  type: Phaser.CANVAS,
  height: 400,
  width: 400,
  parent: 'gameContainer',
  scene: {
    create: create
  }
};

const game = new Phaser.Game(config);

let dataText;

function create() {
  this.input.on('pointermove', (pointer) => {
     updatePoint(pointer);
  });

 dataText = this.add.text (10, 10, 'x, y');
}

function updatePoint(pointer) {
  dataText.text = 'x: ' + pointer.offsetX + ', y: ' + pointer.offsetY;
}

You may have to refactor your code a little bit to get this to work, because the event listener on your DOM element needs to be able to access the game methods. I created a quick codepen showing the setup that worked for me.

like image 179
brae Avatar answered Oct 15 '25 17:10

brae