I’ve been writing this mouse look routine, but I can’t seem to get it right. It’s a first-person view and my player camera is set behind the actual player, so when the player looks around, the camera has to actually orbit around the player on the X and Y axis. When the player lets go of the mouse button, the camera should then slowly snap back to the original (0/0/0) position,
The problem is that when I move around my camera with the mouse, it also affects the Z axis for some reason, and no matter what I do, I can’t seem to restrict the Z-movement and I also can’t seem to be able to get it to snap back smoothly to 0, even if I read the Euler angles. I can’t imagine I’m the only one with this problem, so I thought I’d ask for some help. Below, please find my code. Any advice would be most appreciated.
public Transform mouseCamera;
public float camRotLimitX = 90f;
public float camRotLimitY = 60f;
public float camSensitivity = 4f;
private float snapBack = 0f;
private float currentAngleX = 0f;
private float currentAngleY = 0f;
private float lastRotationX = 0f;
private float lastRotationY = 0f;
void MouseLook ()
{
if ( Input.GetButton ( "Fire2" ) ) // Mouse look is triggered by the right mouse button
{
currentAngleX += Input.GetAxis ( "Mouse X" ) * camSensitivity;
currentAngleY -= Input.GetAxis ( "Mouse Y" ) * camSensitivity;
currentAngleX = Mathf.Clamp ( currentAngleX, -camRotLimitX, camRotLimitX );
currentAngleY = Mathf.Clamp ( currentAngleY, -camRotLimitY, camRotLimitY );
mouseCamera.RotateAround ( transform.position, Vector3.up, currentAngleX - lastRotationX );
mouseCamera.RotateAround ( transform.position, Vector3.right, currentAngleY - lastRotationY );
lastRotationX = currentAngleX;
lastRotationY = currentAngleY;
snapBack = 0.0f;
}
else
{
if ( currentAngleX != 0 )
{
currentAngleX = Mathf.Lerp ( currentAngleX, 0, snapBack );
}
if ( currentAngleY != 0 )
{
currentAngleY = Mathf.Lerp ( currentAngleY, 0, snapBack );
}
snapBack += Time.deltaTime;
mouseCamera.RotateAround( transform.position, Vector3.up, currentAngleX - lastRotationX );
mouseCamera.RotateAround( transform.position, Vector3.right, currentAngleY - lastRotationY );
lastRotationX = currentAngleX;
lastRotationY = currentAngleY;
}
}