I’ve seen a lot of similar questions, but none seem to give me the wanted effect. I have an object in my scene that I want to point at the position of my mouse. Except, it’s 2d gameplay so I just want it to point at the x and the y coordinates of my mouse. I’ve tried different approaches, but it didn’t really work out the way I’d liked it too.
Anyone any suggestions?
I had a similer problem with my top down game.
In my case x is left and right, y is up and down, so I wanted the rotation to be happening around the z axis. If you have a different orientation you will have to edit some of the code.
Here was my solution:
//Aim player at mouse
//which direction is up
Vector3 upAxis = new Vector3(0,0,-1);
Vector3 mouseScreenPosition = Input.mousePosition;
//set mouses z to your targets
mouseScreenPosition.z = transform.position.z;
Vector3 mouseWorldSpace = Camera.mainCamera.ScreenToWorldPoint(mouseScreenPosition);
transform.LookAt(mouseWorldSpace, upAxis);
//zero out all rotations except the axis I want
transform.eulerAngles = new Vector3(0,0,-transform.eulerAngles.z);
If it is a top-down game, you can use Camera.main.ScreenToWorld. This gives you a point to use with LookAt, or by affecting the direction object → point to the object’s forward vector. Just ignore the axe you don’t use.