1

I have been following the Unity in Action book but I've run into an issue with the first person camera vertical rotation code.

sensitivityVert = 9.0f;

public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
private float _rotationX = 0;

void Update()
{
   _rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
   _rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);

   float rotationY = transform.localEulerAngles.y;
   transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}

The problem is that instead of giving limits to where the camera can move, Clamp freezes the camera on a location based on the 2 values provided and doesn't do anything based on mouse input.

Does anyone have any idea on how to fix this?

1 Answers1

1

You need to rewrite clamp for Euler angles because when you getting an angle from transform you always get a positive angle.

public static float RestrictAngle(float angle, float angleMin, float angleMax)
{
    if (angle > 180)
        angle -= 360;
    else if (angle < -180)
        angle += 360;

    if (angle > angleMax)
        angle = angleMax;
    if (angle < angleMin)
        angle = angleMin;
    return angle;
}
OnionFan
  • 479
  • 3
  • 10
  • Thanks a lot for the answer! Unfortunately the same thing happened but I was able to figure out that for whatever reason my inspector was overwriting the script's min and max values to both be 45 and that was causing it to get stuck there. – user13094992 Jun 28 '20 at 12:57
  • Out of so many answers on unity forums, this was the only one that worked for me! Thanks! – Christopher Smit Jun 20 '21 at 18:45