What would be the world eulerAngles of a child object with a given local eulerAngles?

This seems like it should be really simple, but I always seem to struggle with this conceptually.

Given a Transform “T” and a localEulerAngles, I want to know what the world eulerAngles of a child of “T” would be if the child had the given localEulerAngles.

So far, I’ve only been able to get this to work by creating a temp object, setting its parent and localEulerAngles, and then returning its world euler angles. Here’s that code:

public Vector3 GetWorldEulerAngles(Transform T, Vector3 localEulerAngles )
{
    var tempGo = new GameObject("Temp");
    tempGo.transform.SetParent(T);
    tempGo.transform.localEulerAngles = localEulerAngles;
    var retval = tempGo.transform.eulerAngles;
    GameObject.Destroy(tempGo);
    return retval;
}

This feels very ugly, but it does work. I’m trying to figure out how to get the same result without creating the temp object.

So, I want to answer the hypothetical question: “If I added a child to ‘T’ and gave it a particular localEulerAngles, what would its world eulerAngles be?”

I initially though I could use something like return T.rotation * localEulerAngles; but that doesn’t seem to be right. Is there something easy I’m overlooking here? I don’t even see a way to convert a rotation from local to world and vice versa (only converting points or directions, not rotations).

It’s not you, it is that Euler angles are ambiguous.

That’s why we use quaterions. :slight_smile:

All about Euler angles and rotations, by StarManta:

https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html

1 Like

Quaternion * Vector3 is does not combine rotations, the documentation states “Rotates the point point with rotation”. So you’re taking the euler angles as a position and rotating that position with the quaternion rotation.

Using (T.rotation * localRotation).eulerAngles gives you the right result.

There’s really no good way to combine two euler angle rotations, so you need to first convert them to quaternions or rotation matrices and then combine those (or, when working with transform, just take the quaternion representation).

Quaternions and rotation matrices can also inversed, allowing you to do the reverse, calculating the local rotation equivalent to a world rotation, e.g:

(Quaternion.Inverse(T.rotation) * rotation).eulerAngles

1 Like

Indeed that seems to give the identical results as the bad approach I was using. Thanks very much.

And it reinforces how I still always seem to think about this wrong, where I’ll try to rotate a quaternion by an eulerAngle, rather than realizing I can rotate the eulerAngle by the quaternion.

Thanks again. Until the next time I mixes this all up again. :slight_smile: