#Get Mouse Positon and make player look at it

1 messages · Page 1 of 1 (latest)

umbral trellis
#

Hello, I’m making a 2D top-down shooter and I’m currently having trouble figuring out how to get the cursor position in version 6.3, since this is my first time using it. I would also appreciate some help on how to convert this position into an angle, so that the player can face the cursor.

tired merlin
#

To get the mouse position it depends on which input system you're using.

#

By default projects in 6.3 use the new input system

#

in which case you can either create an input action and bind it to the mouse position, or you can directly use Vector2 mousePos = Mouse.current.position.ReadValue();

#

As for "converting the position to an angle" that doesn't make sense without further context. You cannot make an angle out of a single point

#

An angle requires three points or two vectors like AB and AC in the image above

umbral trellis
tired merlin
#

YOu can do this by getting a reference to your camera and doing Vector3 mouseWorldPos = myCamera.ScreenToWorldPoint(mouseScreenPos);

#

You'll probably walso want to set the z position of that world space position to be the same as your player's z position, so assuming you're using a script on the player itself you would do:

Vector3 mouseWorldPos = myCamera.ScreenToWorldPoint(mouseScreenPos);
mouseWorldPos.z = transform.position.z;```
#

And finally you'll want to point your player at the mouse, and to do that we don't need to worry about calculating any angles or anything

#

Depending on if "forward" for your sprite is right or up, you would just do:

Vector3 directionToMouse = mouseWorldPos - transform.position;
transform.right = directionToMouse;
// OR if your "forward" is "up":
transform.up = directionToMouse;```
umbral trellis
#

Wow thats a lot, but thak u very much!

umbral trellis
#

That works really well, thank you!

#

Get Mouse Positon and make player look at it

light light
#

you can also use Quatenrion.LookRotation if you don't want to just set transform.right/etc.

#

this makes more sense in 3D, though

#

LookRotation makes the Z axis point at the target