Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find the mouse position x/y using phaser

I'm having problems, trying to display the mouse position x/y when they click on an image, im using one of the click on and image example that phaser provides.

here is the code

var game = new Phaser.Game(800, 500, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });

var text;
var counter = 0;

function preload () {

    //  You can fill the preloader with as many assets as your game requires

    //  Here we are loading an image. The first parameter is the unique
    //  string by which we'll identify the image later in our code.

    //  The second parameter is the URL of the image (relative)
    game.load.image('Happy-face', 'happy.png'); 

}

function create() {

    //  This creates a simple sprite that is using our loaded image and
    //  displays it on-screen and assign it to a variable
    var image = game.add.sprite(game.world.centerX, game.world.centerY, 'Happy-face');

    //  Moves the image anchor to the middle, so it centers inside the game properly
    image.anchor.set(0.5);

    //  Enables all kind of input actions on this image (click, etc)
    image.inputEnabled = true;
    this.position = new Phaser.Point();
    text = game.add.text(250, 16, '', { fill: '#ffffff' });

    image.events.onInputDown.add(listener, this);

}

function listener () {

    counter++;
    text.text = "Position x/y " + counter + "!";


}
like image 825
Pedro Avatar asked Jan 23 '15 07:01

Pedro


2 Answers

if you want x and y position o f input

game.input.x;
game.input.y;

if you want for mouse specifically

game.input.mousePointer.x;
game.input.mousePointer.y;

the listener function will be like

function listener () {

counter++;
text.text = game.input.mousePointer.x +"/"+game.input.mousePointer.y +     counter + "!";


}
like image 186
Sky Walker Avatar answered Oct 08 '22 10:10

Sky Walker


Just to add that the listener function will be sent 2 parameters: sprite and pointer. So you can do:

function listener (sprite, pointer) { var x = pointer.x; var y = pointer.y; ... }

This will be the most accurate method to use as it accounts for multi-touch devices, where-as accessing input.x/y directly doesn't, it only contains the most recent touch event coordinates (which in a mouse only environment is fine, but not anywhere else).

like image 30
PhotonStorm Avatar answered Oct 08 '22 08:10

PhotonStorm