Problem with negative values when using mathf.clamp to limit rotation
I have encountered a problem in my code. The purpose of this script is to make the main camera rotate on the x and y axis with help of wasd and the mouse when it is close to the edges of the screen.
The problem is when I try to implement limits to the rotation with mathf.clamp. I realize that mathf.clamp doesn't like negative values, but I don't know how to solve it. So when I'm trying to limit a cameras rotation between -15 and 35 on the x axis and between -175 and -105 on the y axis. On the x axis, the rotation stops at 35, but as soon as I go over the 0 value on the x axis, it snaps to 35. As for the y axis, it is constantly locked to -105.
I get that Euler doesn't have negative values, but I have yet to find a workaround for this.
Anyway, here's the code:
using UnityEngine;
public class CameraController : MonoBehaviour {
public float rotSpeed = 20f;
public float rotBorderThickness = 40f;
void Update () {
Quaternion qRot = Camera.main.transform.rotation;
Vector3 rot = qRot.eulerAngles;
if ((Input.GetKey("w") || Input.mousePosition.y >= Screen.height - rotBorderThickness))
{
rot.x -= rotSpeed * Time.deltaTime;
}
if (Input.GetKey("s") || Input.mousePosition.y <= rotBorderThickness)
{
rot.x += rotSpeed * Time.deltaTime;
}
if (Input.GetKey("a") || Input.mousePosition.x <= rotBorderThickness)
{
rot.y -= rotSpeed * Time.deltaTime;
}
if (Input.GetKey("d") || Input.mousePosition.x >= Screen.width - rotBorderThickness)
{
rot.y += rotSpeed * Time.deltaTime;
}
//Here's the problem
rot.y = Mathf.Clamp(rot.y, -175, -105);
rot.x = Mathf.Clamp(rot.x, -15, 35);
Quaternion newRot = Quaternion.Euler(rot);
transform.rotation = newRot;
}
}
Please convert this to a comment ins$$anonymous$$d of an answer- if people see that an answer exists already, sometimes they won't bother checking the question.
In regards to your problem here, $$anonymous$$athf.Clamp has no problem with negative values. Internally, it's literally just "if value is less than $$anonymous$$, value equals $$anonymous$$- if value is greater than max, value is max"- there's nothing to go wrong there. I suspect the problem is the assumption that eulerangles correlates to the values you see in the inspector. Ins$$anonymous$$d of clamping them, try just debug logging the values to the console once a second and see what that looks like.
Well, the rot.x values in the log showed as 345 ins$$anonymous$$d of -15, which is logical because 360 -15 = 345, but If I use 345 in $$anonymous$$athf.clamp it takes the opposite angle as to what I want, where 345 is the largest value and 35 the lowest, when it should be the other way around.