Search code examples
c#unity-game-enginequaternionseuler-angles

Unity Quaternion - get Euler angles of a component B relative to component A


I cannot get my head around Quaternions, and have tried many combination of operators on this (after reading / viewing tutorials). No success - just shows my lack of understanding. Even tried it with angles and atan2() - but all that really showed me was what gimbal lock was. The problem I am trying to solve is:

I have a component (say A, a cube) with some rotation in the world frame of reference (doesn't actually matter what that rotation is, could be orientated any direction).

Then I have another component (say B, another cube) elsewhere in the world space. Doesn't matter what that component's rotation is, either.

What I want to get to in the end are the (Euler) angles of B relative to A, BUT relative to A's frame of reference, not world space. The reason is I want to add forces to A based on B's direction from A, which I can then do with A.rigidbody.addRelativeForce(x, y, z); .

Stuck.


Solution

  • With thanks for the comments, I think I have it.

    For reference, considering a vector and rotation within the same (world frame) coordinates, a new vector representing the original, but viewed from the perspective of local frame coordinates, being those of the original world rotation, can be calculated as:

    static Vector3 createVectorForLocalRotationFrame(Vector3 worldVector, Quaternion worldRotation, bool normalise)
    {
        Vector3 localVector = Quaternion.Inverse(worldRotation) * worldVector;
    
        if (normalise)
            localVector.Normalize();
    
        return localVector;                                                             
    }
    

    The normalise option is just something I needed. Don't ask me how it works, but it appears to be right.