用C#编程,求两个三维向量之间的夹角

我们在平时工作中,经常会需要求两个向量直接的夹角,为了避免后续遗忘,特在此做一个记录

二维向量
 

double getDegAngle2d( const  vector2 v1, const vector2 v2)
{
    double theta = atan2(v2.y, v2.x) - atan2(v1.y, v1.x); //弧度
    if (theta > M_PI)
    {
        theta -= 2*M_PI;
    }
    if (theta < -M_PI)
    {
        theta += 2*M_PI;
    }
    return theta * 180/M_PI; //角度
}

三维向量

/// 
/// 求两个向量绕轴axis 的角度
/// 
/// 
/// 
/// 
private float AngleAroundAxis(Vector3 dirA, Vector3 dirB, Vector3 axis)
 {
    dirA = dirA - Vector3.Project(dirA, axis);

    dirB = dirB - Vector3.Project(dirB, axis);

    float angle = Vector3.Angle(dirA, dirB);

     return angle * (Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) < 0 ? -1 : 1);
}

你可能感兴趣的:(C#,编码技巧,c#,开发语言)