- Home /
Setting a local rotation via script results in a 180 degree difference in actual rotation
I have a character and I'm trying to set some of it's joint's local rotations to certain values (clamping them, to be precise). The results were different from what I've been expecting, so I checked the results during run-time in the inspector. It turns out that whatever value I set programatically, in the end, the joint's rotation will be different by exactly 180 degree (plus or minus), as can be seen from the editor or checked via code. In a related questions, it was recommended to use go.localEulerAngles
, but this results in the same problem. Can you tell me why this is happening?
Current code:
Vector3 jointRot = joint.localEulerAngles; // Getting the current rot
Debug.Log (joint.name +" before: "+jointRot);
jointRot.x = Mathf.Clamp (jointRot.x, jointMin.x, jointMax.x);
jointRot.y = Mathf.Clamp (jointRot.y, jointMin.y, jointMax.y);
jointRot.z = Mathf.Clamp (jointRot.z, jointMin.z, jointMax.z);
Debug.Log (joint.name + " fixing: " + jointRot);
joint.localEulerAngles = jointRot; // Setting it to the clamped version
Debug.Log (joint.name +" after: "+joint.localEulerAngles);
Previously, I was using this line to set the altered rotation, but it gives the exact same results:
joint.localRotation = Quaternion.Euler (jointRot);
The output (elbow as example) on the console reads as follows:
lowerarm_r before: (322.5, 140.2, 14.2)
lowerarm_r fixing: (160.0, 140.2, 0.0)
lowerarm_r after: (20.0, 320.2, 180.0)
So although I'm setting localEulerAngles to (160, 140, 0)
, it will now hold the value (20, 320, 180)
, which is different by 180 degree each. The documentation on localEulerAngles reads:
Unity automatically converts the angles to and from the rotation stored in Transform.localRotation
I assume this is what is causing the issue, but I don't understand why. I would assume all this does is convert the euler angels to a Quaternion.
To add to the confusion, sometimes it seems to work just as expected:
lowerarm_r before: (7.2, 347.8, 1.7)
lowerarm_r fixing: (10.0, 347.8, 0.0)
lowerarm_r after: (10.0, 347.8, 0.0)
I'm grateful for any insight.