- Home /
Identify range of rotation / eulerAngles - Not working for backward
I want to identify the range of rotation of an object. Looking forward works, but not backwards. What is the tip for work? Why rotation.eulerAngles not working in this case? Tks.
var quantRot : float;
function Update () {
transform.eulerAngles.y = quantRot;
if (transform.rotation.eulerAngles.y >= 270f || transform.rotation.eulerAngles.y <=90f){ // works
print ("Car looking to north in the world");
}
if (transform.rotation.eulerAngles.y <= 271f || transform.rotation.eulerAngles.y >=91f){ // doesn't work
print ("Car looking to south in the world");
}
}
Answer by robertbu · Jun 01, 2013 at 08:18 PM
Reading from eulerAngles and expecting a specific value often fails. That's because there are multiple eulerAngle representations for a physical representation, and you cannot depend on on Unity to maintain any single representation. For example if you set your rotation to (180,0,0) in a script, and then use a Debug.Log() to print the rotation out, you will get (0,180,180)...the same physical rotation but represented differently.
Given your use of 270 and 90, I'm not sure of how you have your car setup with respect to what is forward. If you had a traditional car where forward was the side of the car facing positive 'z' when the roation was (0,0,0), and if north is positiive 'Z', then you can solve this problem using Vector3.Angle():
if (Vector3.Angle(transform.forward, Vector3.forward) < some_angle) {
// The car is headed north
}
Vector3.Angle() returns an unsigned angle. 'some_angle' defines how close you have to be to pointing north before the code fires. A value of 90, would cover all 180 degrees.
Answer by aldonaletto · Jun 01, 2013 at 08:42 PM
eulerAngles are tricky: always assign the XYZ values at once, and only trust in the Y value when X and Z are 0:
function Update () {
transform.eulerAngles = Vector3(0, quantRot, 0);
if (transform.eulerAngles.y >= 270f || transform.eulerAngles.y <=90f){ // works
print ("Car looking to north in the world");
}
if (transform.eulerAngles.y <= 271f || transform.eulerAngles.y >=91f){ // doesn't work
print ("Car looking to south in the world");
}
}
Anyway, there's a better method to find whether the object is looking to world north or south:
if (Vector3.Dot(transform.forward, Vector3.forward)>=0){
print ("Car looking to north in the world");
} else {
print ("Car looking to south in the world");
}
The dot product returns a value proportional to the cosine of the angle between the two vectors: this value is positive when the absolute angle is below 90 degrees, and negative when it's higher (90 degrees gives exactly 0). This makes the dot product very useful when deciding if something is in front or behind the character:
var targetDir = target.position - transform.position;
if (Vector3.Dot(targetDir, transform.forward) > 0){
// target is in front of this object
} else {
// target is behind this object
}
Your answer