- Home /
Issue with clamping camera
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);
}
Answer by tategarringer · Dec 12, 2020 at 08:53 PM
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
.
I tried all the changes but clamping is still not working for some reason
float pitch = $$anonymous$$athf.Clamp(Input.GetAxis("$$anonymous$$ouse Y") * 100, -60, 80);
float yaw = Input.GetAxis("$$anonymous$$ouse X") * 100 * Time.deltaTime;
Camera.main.transform.Rotate(-pitch * Time.deltaTime, 0, 0, Space.Self);
Camera.main.transform.Rotate(0, yaw, 0, Space.World);
By "not working" what exactly do you mean? Is it moving beyond the parameters of the $$anonymous$$athf.Clamp
function? No change whatsoever? Have you tried to Debug.Log()
your pitch value as it's running? It's hard to go off a generic "not working".
I tried to debug but the numbers are all over the place, so I wonder if Space.Self or something else is causing issues. The numbers are exceeding the clamp values though
OP is trying to clamp the angle of their camera, not the magnitude of its rotation, btw. The code here will limit how much that rotation can change each update tick, but not the rotation itself.