# Having trouble with LookRotation at mouse on one axis

I have a 2D game with a vehicle that moves left or right on the X-axis and a turret that points up a long the Y-axis. I tried writing my own script getting this turret to rotate left or right on the Z-axis to look at the mouse cursor, but it didn’t quite work out as nothing is happening. The turret won’t move at all. Here is my script:

``````public float rotateSpeed;

void FixedUpdate () {

Vector3 mousePos = Input.mousePosition;
Vector3 lookPos = Camera.mainCamera.ScreenToWorldPoint(mousePos);
lookPos.x = 0;
lookPos.y = 0;

Quaternion targetRotation = Quaternion.LookRotation(lookPos - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotateSpeed);

}
}
``````

I understand basically what LookRotation does but I think I’m plugging the wrong info into it. What am I doing wrong here?

Two issues here. For the calculation of ScreenToWorldPoint(), the ‘z’ parameter needs to be the distance in front of the camera. By default ‘mousePosition’ as a ‘z’ value of 0.0, so ScreenToWorldPoint() will return the position of the camera. Say your camera is at -10 on the ‘z’ axis and your 2D game has played a ‘z’ = 0.0. You would set ‘mousePos.z = 10.0f’ before you call ScreenToWorldPoint(). Again, you are setting the ‘z’ parameter to the positive distance in front of the camera to calculate the point.

The second issue is the axis that LookRotation uses as up. By default, it use Vector3.up, but since you are rotating around the ‘z’ axis, you need to use Vector.forward. Putting the two changes together:

``````public float rotateSpeed = 45.0;

void Update () {
Vector3 mousePos = Input.mousePosition;
mousePos.z = 10.0f;
Vector3 lookPos = Camera.mainCamera.ScreenToWorldPoint(mousePos);

Quaternion targetRotation = Quaternion.LookRotation(lookPos - transform.position, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotateSpeed);
}
``````

Note that this code assumes that you are aiming the forward of the game object this script it is attached to at the mouse position.