- Home /
[SOLVED]2D lookAt is off, any ideas?
Hello everyone and thanks for your time. I recently started a small personal project and have noticed that my look at is off most of the time. It will match up sometimes but not all the time and that just won't work for me.
The red line is leading to the mouse cursor while the blue line is where the turret is firing to.
Here is the bit of code I have doing it
lookAtPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Quaternion rot = Quaternion.LookRotation(transform.position - lookAtPos, Vector3.forward);
transform.rotation = rot;
transform.eulerAngles = new Vector3(0, 0, transform.eulerAngles.z);
That is in the update function.
As a guess, add between line and 2:
lookAtPos.z = transform.position.z;
Assu$$anonymous$$g an orthographic camera, this line:
lookAtPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
...will produce an x,y position of the finger but a 'z' position at the camera.
ScreenToWorldPoint isn't very obvious how it works. The Z coordinate is extremely important because it represents how far INTO the scene FRO$$anonymous$$ the camera's position.
Setting lookAtPos.z to transform.position.z just makes the turret move at 90 degree increments ins$$anonymous$$d of actively tracking the cursor
Answer by robertbu · Oct 17, 2014 at 11:47 PM
What side of your gun is the front when the gun has the rotation of (0,0,0)? I suspect you are looking at 2D here with the front on the right or up. If so, you cannot use LookAt() in the way you are using it here. My assuming was that since your original code was sorta working that font faces positive 'z' when the rotation is (0,0,0). For rotation of an object where front is the right side and the camera is facing has rotation (0,0,0), you can do:
Vector3 dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
This is no rotation applied to it all, the top part is what faces the mouse, however it is parented to an object that is rotated 180 on the z axis. I don't think that would be an issue though.
The bit of code you posted is 90 degrees off.
EDIT:
I took the image into an editor and rotated it so that the barrel would be the right edge and it works like a charm, thanks for that bit of code!
Your answer
![](https://koobas.hobune.stream/wayback/20220613165316im_/https://answers.unity.com/themes/thub/images/avi.jpg)