How to get the X and Y positions of the mouse


#1

So I’m working on a 2D Battle Royale game, similiar to surviv.io, although pretty different. I’ve been trying to get the player to face towards the mouse, using

this.entity.lookAt();

However, I can’t seem to find a way to get the X and Y positions of the mouse. I’ve taken a look at pretty much everything in the API Refference, but I can’t find anything that works. Here’s the link to my project: https://playcanvas.com/editor/project/594696 You can find the code that I’m working on in the Movement.js script in the Scripts folder.


#2

Unfortunately, you have to listen for the mouse move event and the x/y position data of the mouse will be in the event https://developer.playcanvas.com/en/api/pc.MouseEvent.html#x

I normally store the x/y in the script properties so I can use them else where.

I believe it was done this way to mirror the touch API where there is no concept of ‘position’ unless the user was touching and moving their finger on the screen.


#3

I figured that was the way that I was supposed to do it, but how exactly would I construct that event? I’m new to PlayCanvas, and although I’ve had past experience in JS, I haven’t had a lot of experience with events, and I’m a bit confused as to how to read the API refference.


#4

There’s an example here on how to listen to the mouse events https://developer.playcanvas.com/en/tutorials/mouse-input/


#5

Thank you. That helps a lot. I saw that before, but I didn’t quite get it… facepalm I feel stupid :rofl:

Thanks!