How to make an object point towards the mouse?

I’m attempting to make an object (the main character/avatar) point towards the mouse. I have it facing upright, so the Z axis is the one that I need to rotate appropriately, since this is a 2D Project. After succesfully getting the X and Y mouse positions, I quickly realized that the lookAt command wouldn’t work. So I decided to use the SetEulerAngles.

Right now, I’m using the code below:

Test.prototype.onMouseMove = function(event) {
    var angle = Math.atan2(event.x, event.y);
    this.entity.setLocalEulerAngles(0, 0, angle);
};

I checked the math multiple times, and it seems to be correct. However, when launched, the character just moves SLIGHTLY towards the mouse. Since I’m pretty sure the math is right, I tried this.entity.setRotation and this.entity.setLocalRotation, but both make the sprite disappear instead. If someone could offer a fix for this, that would be wonderful, as I’m completely stumped.

Here’s the link to my editor: https://playcanvas.com/editor/scene/726439

This question has been asked, kind of. My understanding is that Euler angles work kinda funny in PlayCanvas.

Hopefully this helps!

You are using the mouse position relative to the screen position, not the object.

Use worldToScreen on the object which will get you the screen position of the object, subject that position from the mouse screen position and then do the atan2.

Inversely, use screenToWorld on the mouse position to get the projected world position, ensure that it is on the same plane as the object and use entity.lookAt (assuming the forward direction of the object is on the -Z).

OK, but how would I do that? I tried this:

Test.prototype.onMouseMove = function(event) {
    var cameraEntity = this.app.root.findByName("Camera");
    cameraEntity.camera.screenToWorld(event.x, event.y, 1, this.pos);
    this.entity.lookAt(0, 0, this.pos);
};

However, it just disappears. I made sure that the front of my object is facing the -Z direction. I also tried putting this.pos in both the X or Y positions instead of Z. The only one that “worked” was X, but it rotated the wrong way.

(sorry that this is late. I’m not too active on here)

Test.prototype.onMouseMove = function(event) {
    var angle = Math.atan2(event.x, event.y);
    this.entity.setLocalEulerAngles(0, 0, angle);
};

Going back a bit. Using the mouse coords for atan2 doesn’t work as it’s taking the vector from the origin of the screen which is the top left.

51

What you need is vector from the screen position of object to the mouse cursor.

Below is an example project using the atan2 method as it’s what you were originally used.

https://playcanvas.com/editor/scene/733295

Ah… I didn’t realize that the origin was at the top left.

That really helps. Thank you!