Question by
Play Creatively · Dec 27, 2015 at 11:01 AM ·
if-statementsif statement
mathf.abs(0) is higher than 90, why?
What I don't understand is that instead of changing direction at 90° and -90° (like it should) it instead first changes direction at 90° but then changes again at 0°, that doesn't add upp!
public class NewBehaviourScript : MonoBehaviour {
[Range(0f,150f)]
public float speed;
public int direction = 1;
void Update ()
{
Vector3 rotation = transform.rotation.eulerAngles;
direction = Mathf.Abs(rotation.z) > 90f ? -direction : direction;
transform.Rotate(0f, 0f, direction * speed * Time.deltaTime);
}
}
Comment
Best Answer
Answer by mikelortega · Dec 28, 2015 at 10:11 AM
transform.rotation.eulerAngles is an interpretation of the Quaternion that Unity uses internally. The values go from 0 to 360. So your direction changes when the value goes below 0 (because it actually jumps to 360).
You should do this instead:
direction = Quaternion.Angle(transform.rotation, Quaternion.identity) > 90f ? -direction : direction;