Vector2.Angle 的 bug

获取角度 ,官方提供了 Vector2.Angle 来得值,他的值是在 0  ,180之间

原始代码是

    public static float Angle(Vector3 from, Vector3 to)
    {
        return Mathf.Acos(Mathf.Clamp(Vector3.Dot(from.normalized, to.normalized), -1f, 1f)) * 57.29578f;
    }

注意最后一个是 180/ 3.1415926...  =  57.29578f;正常角度是 360,所以我们可以先 做出 -180,180之间

你可以

  float angle_180(Vector2 from, Vector2 to)
    {
        Vector3 v3;
        Vector3 v3_from = new Vector3(from.x, from.y, 1);
        Vector3 v3_to = new Vector3(to.x , to.y  , 1);
        v3 = Vector3.Cross(v3_from, v3_to);
        if (v3.z > 0)
        {
            return Vector2.Angle(from, to);
        }
        else
        {
            return -Vector2.Angle(from, to);
        }
    }

 也可以这样写

   float VectorAngle(Vector2 from, Vector2 to)
    {
        float angle;

        Vector3 cross = Vector3.Cross(from, to);
        angle = Vector2.Angle(from, to);
        return cross.z > 0 ? -angle : angle;
    }

 0,360之间可以这样写

 if (angle < 0)
                {
                    angle = 360 + angle;
                }

但是,我今天要说的不是这些,这些百度都可以知道。

我说的是 Vector2.Angle  的 bug以上的操作,仅仅对于 起始点0,0  有效,如果起始点 其他坐标,那么 他将会有误差

那么我们改怎么做呢?

这样写,可以没有误差,注意 initPosition是目标坐标

 Vector2 v2 = (mousePosition - initPosition).normalized;
 float angle = Mathf.Atan2(v2.y, v2.x)*Mathf.Rad2Deg;
 if(angle < 0)
     angle = 360 + angle;

 参考老外聊天,这个问题也是我 发现后 google 找的。

http://answers.unity3d.com/questions/444414/get-angle-between-2-vector2s.html

原文地址:https://www.cnblogs.com/big-zhou/p/4793575.html