I can’t wrap my head around rotations. I simply want to say: if targetObject’s rotation is less than 90 and greater than -90 (as displayed in the editor) than execute something. But I can’t get it to work and I keep getting strange results. Its my understanding (please correct me if I’m wrong and explain to me like I’m 5) that Unity stores rotations as Quaternions internally and what you see in the editor in the transform component are euler angles. But I must be missing something. My code below yields bizarre results.
public Transform targetObject;
public Vector3 targetObjectRot;
targetObjectRot = targetObject.localRotation.eulerAngles;
… and hit run, targetObjectRot displays the correct values until I rotate targetObject into the negative (lets say -9 on the x axis) at which point targetObjectRot displays the number 351 for the x axis. So how do I get around this?
Edit: found out how to calculate negative euler angles here. Rotating things in Unity!
Because the euler angles are constrainted from 0 to 360 it means you won’t get any negative angles. If you want -90 you would need to use 270 instead (360-90)
Thanks friend! I see that now. For anyone else who stumbles on this thread, I should also add that the rotation values you see in the editor are in fact the local euler angle values.
Yes, Unity stores rotations as Quaternions and displays the Euler angles in the editor.
First, there’s a difference between transform.rotation and transform.localRotation. Local Rotation is the Quaternion for what you see in the Unity editor, and it’s the rotation relative to its parent. Rotation is the total rotation, that you would get from adding its local rotation and all of its parents’ rotations. Similarly, localEulerAngles is the local rotation in Euler form (what you actually see in the unity editor) and eulerAngles is the combined rotation including all the parents.
As for your second post, -9 degrees is the same thing as 351 degrees. You could check if it’s either between -90 and 90 or between 270 and 360. Simpler might be to use Mathf.DeltaAngle ( Unity - Scripting API: Mathf.DeltaAngle )
if (Mathf.Abs(Mathf.DeltaAngle(transform.localEuler.x, 0)) < 90f)
//do stuff
Delta angle will get the smallest distance between the angles regardless of how they’re expressed (-9 or 351 will be treated the same). Here I’m getting the absolute value of the difference between the angle and 0, and checking if it’s less than 90, which should work for you.