I’m trying to clamp the angle of my camera but clamping is not working
public void MoveCamera()
{
float pitch = Input.GetAxis("Mouse Y") * 100 * Time.deltaTime;
float yaw = Input.GetAxis("Mouse X") * 100 * Time.deltaTime;
ClampAngle(pitch);
Camera.main.transform.Rotate(-pitch, 0, 0, Space.Self);
Camera.main.transform.Rotate(0, yaw, 0, Space.World);
}
void ClampAngle(float angle)
{
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
yDeg = Mathf.Clamp(angle, -60, 80);
}
Firstly, looks like you’re setting variable yDeg
to the clamped value of your angle and then never using it. Also, realistically, if you’re clamping the angle value between -60 and 80, there’s no reason to have the logic:
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
The subsequent Mathf.Clamp
dictates that even if either scenario occurs, it’ll clamp it to -60 or 80 respectively. Secondly, I’m sure you’re aware that Input.GetAxis
returns a normalized value between -1 and 1, hence your inclusion of a multiplicative factor, but then you go and multiply it by Time.deltaTime
, so the scenario where value clamping would be necessary will never occur unless your framerate is INCREDIBLY slow.
You could ditch the ClampAngle()
method entirely and sum it up in one line:
float pitch = Mathf.Clamp(Input.GetAxis("Mouse Y") * 100, -60, 80);
And then change your rotation function to:
Camera.main.transform.Rotate(-pitch * Time.deltaTime, 0, 0, Space.Self);
Tested and working with MoveCamera()
called in Update()
, this will ensure that your angle value is clamped BEFORE you apply your “angle per frame” calculation utilizing Time.deltaTime
.