How to restrict rotation properly

How do I restrict rotation angles? The rotation just keeps slipping through the limit and stopping forever. When I set 355 as a limit, it stops at 354.993 or something. Can something be done about it? Is the problem with Update frequency?

I am using this code:

if(Input.GetAxis("Mouse X")<0)
{	
	if ((transform.rotation.eulerAngles.y < 4) || (transform.rotation.eulerAngles.y > 355))
	{
		transform.RotateAround(cameraFocus.position, Vector3(0, -1, 0), 5 * Time.deltaTime);
		print(transform.rotation.eulerAngles.y);
	}
}

//right
if(Input.GetAxis("Mouse X")>0)
{
	if ((transform.rotation.eulerAngles.y < 4) || (transform.rotation.eulerAngles.y > 355))
	{
		transform.RotateAround(cameraFocus.position, Vector3.up, 5 * Time.deltaTime);
		print(transform.rotation.eulerAngles.y);
	}
}

I need this for synching cursor movement with camera rotation, obviously.

Please, help.

Not clear what this code is trying to do. It looks like you’re trying to limit the camera rotation to +/- 5 degrees, which seems a bit small.

Personally, I’d insert a dummy GameObject which sits at the cameraFocus position, with the camera parented to that. Then you just set the dummy’s transform.rotation.eulerAngles, rather than doing a RotateAround which will gradually accumulate floating point error. You can then easily clamp the Y rotation to exactly what you want.

You can use Quaternion.RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta) function to restrict rotation:

Quaternion ClampRotationXByLookDirection(Quaternion curentRotation)
{
    Vector3 lookDirectionX = Vector3.ProjectOnPlane(lookDirection, Vector3.right).normalized;
    Quaternion lookRotation = Quaternion.LookRotation(lookDirectionX);
    Quaternion towardsRotation= Quaternion.RotateTowards(lookRotation, curentRotation, lookDeltaX);
    return towardsRotation;
}

Quaternion ClampRotationYByLookDirection(Quaternion curentRotation)
{
    Vector3 lookDirectionY = Vector3.ProjectOnPlane(lookDirection, Vector3.up).normalized;
    Quaternion lookRotation = Quaternion.LookRotation(lookDirectionY);
    Quaternion towardsRotation= Quaternion.RotateTowards(lookRotation, curentRotation, lookDeltaY);
    return towardsRotation;
}