首页 > 技术文章 > 数学

skylinee 2016-09-14 13:49 原文

    //1.-180 180
    //2.from,to为xz平面上的向量
    float SignedAngle(Vector3 from, Vector3 to)
    {
        float sign = Mathf.Sign(Vector3.Cross(from, to).y);
        return sign* Vector3.Angle(from, to);
    }

  以上必须限制from,to为xz平面上的向量,。对任意两向量的angle,只能求出0,180之间的值(不带+-符号),除非给定两向量确定的平面的法向量。所以计算任意两向量的signed angle :

/// <summary>
/// Determine the signed angle between two vectors, with normal 'n'
/// as the rotation axis.
/// </summary>
public static float AngleSigned(Vector3 v1, Vector3 v2, Vector3 n)
{
    return Mathf.Atan2(
        Vector3.Dot(n, Vector3.Cross(v1, v2)),
        Vector3.Dot(v1, v2)) * Mathf.Rad2Deg;
}

  总结:只有先确定平面,用两向量的差积来表示“from到to是逆时针还是顺时针”才有意义 (就才能进一步用作angle的signed判定)

推荐阅读