- Home /
LookAt To Only Rotate on Y Axis
Hello, i have a player that faces where my mouse pointer is at the scene, but he is rotating ALL the axis, how i can rotate just the Y axis ?
void Update () { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); if (Physics.Raycast (ray, out hit, 100)) { //Vector3 lookatposition = new Vector3(0,0,0); //lookatposition.y = hit.point.y; transform.LookAt (new Vector3 (hit.point.x, hit.point.y, hit.point.z)); //transform.LookAt(lookatposition); } } }
Answer by KittenSnipes · Mar 06, 2018 at 03:09 AM
You can do something like that but there is a lot of other ways that may fit your needs better. Not sure if this works or not because I am not really at my computer to test it:
void Update () {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit, 100)) {
//Vector3 lookatposition = new Vector3(0,0,0);
//lookatposition.y = hit.point.y;
transform.LookAt (new Vector3 (0, hit.point.y, 0));
//transform.LookAt(lookatposition);
}
}
Answer by jshaw3 · Aug 21, 2019 at 07:28 PM
I was using ARFoundation and had a character I always wanted to face the AR Camera. I was having some trouble getting lookAt to work correctly and only rotating on the Y-axis. Using lookat the character seemed to always rotate on all 3 axis.
I found an old Reddit post talking about Mathf.Atan2. I found it really helpful to calculate the angle between two points and rotate the character on the y axis only. Found it very helpful.
https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html
Original Reddit post is here: https://www.reddit.com/r/Unity3D/comments/1m1dzf/c_transformlookat_on_y_axis_only/