1
votes

I am using quaternions in my game to calculate some basic angles.

Now I am trying to get the angle of a quaternion, given a certain axis. So, given a quaternion and a new axis. Can I get the projected angle back?

To me, it seems like a solid way to calculate the signed angle between two vectors. The code is written in Unity3D C#, but this does not necessarily has to be the case. It's more of a general method.

public static float DirectionalAngle(Vector3 from, Vector3 to, Vector3 up)
{
    // project the vectors on the plane with up as a normal
    Vector3 f = Vector3.Exclude(up, from);
    Vector3 t = Vector3.Exclude(up, to);

    // creates an angle-axis rotation
    Quaternion q = Quaternion.FromToRotation(f, t);

    // do something to get the angle out of the quaternion,
    // given the new axis.
    // TODO: Make this method. Doesn't exist.
    Quaternion q2 = Quaternion.GetAngleFromAxis(q, Vector3.right);

    return q2.Angle(q2);
}

I can always get the angle and axis from the quaternion, as well as x,y,z,w and the euler angles. But I don't see a way to get the projected angle from the quaternion on the axis.

1

1 Answers

1
votes

I found it! The only thing I had to do was rotate the quaternion in such a way that it is oriented in the local space. The method seems to be sound for all planes I've tested it on.

public static float DirectionalAngle(Vector3 from, Vector3 to, Vector3 up)
{
    // project the vectors on the plane with up as a normal
    Vector3 f = Vector3.Exclude(up, from);
    Vector3 t = Vector3.Exclude(up, to);

    // rotate the vectors into y-up coordinates
    Quaternion toZ = Quaternion.FromToRotation(up, Vector3.up);
    f = toZ * f;
    t = toZ * t;

    // calculate the quaternion in between f and t.
    Quaternion fromTo = Quaternion.FromToRotation(f,t);

    // return the eulers.
    return fromTo.eulerAngles.y;
}