Reputation: 39
I am trying to check if my object's z rotation value comes between two given values. As shown below, the value to check is between -1 and +1. When my object is in negative such as -0.5, it is never called. Works perfect for positive values above 0, but is never called when it is under 0.
void Update () {
if (transform.eulerAngles.z <= 1 && transform.eulerAngles.z >= -1) {
Debug.Log ("object is in between");
}
}
Okay so I found the problem, when I added a Debug.Log (transform.eulerAngles.z);
The values lesser than 0, starts from 360 instead of printing negative values. How do I fix it?
Upvotes: 0
Views: 943
Reputation: 90739
eulerAngles
in general are always a bit unreliable for certain things.
The reason is that internally Unity doesn't store these but stores rotations as Quaternion
. However, there are multiple ways of how to represent a Quaternion
in euler space and eulerAngles
just decides for the best human readable.
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.
Easier in my eyes would be to not think in rotation angles at all.
An equal way to make your check rather simply vector based would be checking if the Vector3.Angle
between the global Vector3.up
vector and your local transform.up
is within your threshold
if(Vector3.Angle(Vector3.up, transform.up) <= 1f)
{
Debug.Log ("object is in between");
}
Upvotes: 2
Reputation: 39
Since Euler Angles in Unity work this way (less than 0 is basically less than 360), I changed my code as:
if ((transform.eulerAngles.z >= 0 && transform.eulerAngles.z <= 1f) || (transform.eulerAngles.z >= 358f && transform.eulerAngles.z <= 360f)) {
Debug.Log("object is in between");
}
Upvotes: 0