tchock
tchock

Reputation: 245

Incrementing Euler angles beyond 360 degrees

I'm a bit confused about some documentation for Unity pertaining to Euler angles. I just want to know if I'm not understanding a difference, or the sample does not follow the best practice. The documentation here states:

Only use this variable to read and set the angles to absolute values. Don't increment them, as it will fail when the angle exceeds 360 degrees. Use Transform.Rotate instead.

Meanwhile, the code sample appears to be using increments that could exceed 360 degrees:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public float yRotation = 5.0F;
    void Update() {
        yRotation += Input.GetAxis("Horizontal");
        transform.eulerAngles = new Vector3(10, yRotation, 0);
    }
    void Example() {
        print(transform.eulerAngles.x);
        print(transform.eulerAngles.y);
        print(transform.eulerAngles.z);
    }
}

Wouldn't incrementing a variable and then using that variable to set the value absolutely still run the risk of exceeding 360 degrees if the variable is over 360 degrees?

Upvotes: 2

Views: 4642

Answers (2)

Sohail Bukhari
Sohail Bukhari

Reputation: 254

When you rotate your Object using euler angles then when it reaches 360 and try to exceed further, it becomes (minus)-360 and gradually increase from -359 to -1.

After executing following code your values will not exceed from 360 and will remain positive.

float rotateAngle = rotateObject.transform.localEulerAngles.y;
// Convert negative angle to positive angle
rotateAngle = (rotateAngle > 180) ? rotateAngle - 360 : rotateAngle;
rotateObject.transform.localEulerAngles = new Vector3(rotateObject.transform.localEulerAngles.x, rotateAngle, rotateObject.transform.localEulerAngles.z);

Upvotes: 2

Lincoln Cheng
Lincoln Cheng

Reputation: 2303

There are differences. When doing:

transform.eulerAngles.y += 1F;

You are invoking the += operator in Vector3.

However, when you set eulerAngles this way:

float newY = transform.eulerAngles.y + 1F;
transform.eulerAngles = new Vector3(.., newY, ..);

You are invoking a setter in Transform, and inside this setter, it probably includes the action of updating Transform.rotation.

The difference is that Unity can implement the updating logic in Transform class instead of the Vector3 class, which makes much more sense there.

We can verify this further below in the documentation:

Do not set one of the eulerAngles axis separately (eg. eulerAngles.x = 10; ) since this will lead to drift and undesired rotations. When setting them to a new value set them all at once as shown above. Unity will convert the angles to and from the rotation stored in Transform.rotation.

Upvotes: 1

Related Questions