0

I have the following code:

if (Input.GetKeyDown(KeyCode.A))
{
    var rot = switchTransform.localEulerAngles;
    Debug.Log(rot);
    rot.x = 150;
    switchTransform.localEulerAngles = rot;
}

When I click 'A', the switchTransform switches from (30, 0, 0) to (150, 0, 0) in the inspector and (30, 0, 0) to (30, 180, 180) in the console.

It works correctly if I write it like this:

angle = 150f;
if (Mathf.Abs(angle) <= 180 && Mathf.Abs(angle) > float.Epsilon)
{
    angle = 180 - angle;
}
if (Input.GetKeyDown(KeyCode.A))
{
    var rot = switchTransform.localEulerAngles;
    rot.x = angle;
    switchTransform.localEulerAngles = rot;
}

Why does it happen, and is there a better way to work around it?

This is the switch transform, as you can see it has unusual pivot.

switchTransform

SagiZiv
  • 932
  • 1
  • 16
  • 38
  • Unity stores rotations as Quaternions and translates them to euler angles for your ease of use. It has some funny side effects. You can try to do what you want using Unity's various helper functions for working with quaternions, without ever going to euler angles. – Verpous Dec 29 '22 at 13:53
  • Read [eulerAngles](https://docs.unity3d.com/ScriptReference/Transform-eulerAngles.html) and in particular the part about `When you read the .eulerAngles property, Unity converts the Quaternion's internal representation of the rotation to Euler angles. Because, there is more than one way to represent any given rotation using Euler angles, the values you read back out may be quite different from the values you assigned. This can cause confusion if you are trying to gradually increment the values to produce animation.` – derHugo Dec 29 '22 at 14:02

0 Answers0