I have an issue where the following chunk of script sticks when the camera reaches the edge of the “upDownRange”(which is meant to limit vertical mouse look so your head doesn’t do backflips on your neck.). the camera stops moving and can’t move back in range. Does anyone have any ideas on how to fix this?
I have the method it’s contained in called in Update.
rotY = Input.GetAxis("Mouse Y") * mouseSensitivity;
rotX = Input.GetAxis("Mouse X") * mouseSensitivity;
if (Camera.main.transform.rotation.x <= upDownRange && Camera.main.transform.rotation.x >= -upDownRange)
{
Camera.main.transform.Rotate(-rotY, 0, 0);
}
transform.Rotate(0, rotX, 0);
Well for one you are trying to read Camera.main.transform.rotation.x which is a mistake because rotation is a Quaternion and the x part does not mean what you think it means.
You should do something like this:
float pitch = 0;
void Update() {
rotY = Input.GetAxis("Mouse Y") * mouseSensitivity;
rotX = Input.GetAxis("Mouse X") * mouseSensitivity;
pitch += rotY;
pitch = Mathf.Clamp(pitch, -85, 85);
Camera.main.transform.localEulerAngles = new Vector3(pitch, 0, 0);
transform.Rotate(0, rotX, 0);
}
You are a saint, thank you very much. It works great. if anyone comes on this looking for code to rip you should switch the “pitch += rotY;” to “pitch -= rotY;” otherwise the look is inverted
DRY principle! Don‘t repeat yourself. It‘s not just slower, and makes code harder to read. Try this instead:
var cameraTransform = Camera.main.transform;
if (cameraTransform.rotation.x <= upDownRange && cameraTransform.rotation.x >= -upDownRange)
{
cameraTransform.Rotate(-rotY, 0, 0);
}