- Home /
Weird issue with clamp on Rotation
Hi So I have managed to clamp the rotation of an object which controls my camera, However, I have run into a strange issue. The clamp works when the rotation is in positive values, but as soon as it goes into the negative values it immediately snaps to the max angle for some reason.
Here is my code:
public GameObject target;
public float rotateSpeed = 5;
public float minConstraintsX, maxConstraintsX;
Vector3 offset;
void Start()
{
offset = target.transform.position - transform.position;
}
void LateUpdate()
{
float horizontal = Input.GetAxis("Horizontal") * rotateSpeed;
float vertical = Input.GetAxis("Vertical") * rotateSpeed;
target.transform.Rotate(0, horizontal, 0, Space.World);
target.transform.Rotate(vertical, 0, 0);
target.transform.localEulerAngles = new Vector3(Mathf.Clamp(target.transform.localEulerAngles.x, minConstraintsX, maxConstraintsX), target.transform.localEulerAngles.y, 0);
float desiredAngleY = target.transform.eulerAngles.y;
float desiredAngleX = target.transform.eulerAngles.x;
Quaternion rotation = Quaternion.Euler(desiredAngleX, desiredAngleY, 0);
transform.position = target.transform.position - (rotation * offset);
transform.LookAt(target.transform);
}
The Vector 3 is the issue I believe but I haven't run into something like this before.
Thanks in Advanced
Answer by unity_ek98vnTRplGj8Q · Dec 20, 2019 at 03:58 PM
From https://docs.unity3d.com/Manual/QuaternionAndEulerRotationsInUnity.html, it is generally not good practice to read, modify, write EulerAngle values.
// rotation scripting mistake #2
// Read, modify, then write the Euler values from a Quaternion.
// Because these values are calculated from a Quaternion,
// each new rotation might return very different Euler angles, which might suffer from gimbal lock.
void Update ()
{
var angles = transform.rotation.eulerAngles;
angles.x += Time.deltaTime * 10;
transform.rotation = Quaternion.Euler(angles);
}
Instead, keep track of your own Vector3 and just write the angles every frame using that.
public Vector3 localEulers;
void Update(){
localEulers += new Vector3(deltaX, deltaY, deltaZ);
transform.localRotation = Quaternion.Euler(localEulers);
}
Likely the issue that you are having is that when reading the x value its not going negative but instead jumping to 360 degrees, which your script will clamp to the max angle. If you want to see what is going on, try printing the angles Debug.Log(target.transform.localEulerAngles
before you clamp them.
Your answer
![](https://koobas.hobune.stream/wayback/20220612220421im_/https://answers.unity.com/themes/thub/images/avi.jpg)