美文网首页
Unity 平面点到直线的距离

Unity 平面点到直线的距离

作者: 杨树叶的杨 | 来源:发表于2017-12-29 10:56 被阅读0次

    public static float disPoint2Line(Vector2 point1, Vector2 point2, Vector2 position)//point1和point2为线的两个端点
    {
    float accuracy = 0.01f;
    float distance = 0;
    float a = Vector2.Distance(point1,point2);// 线段的长度
    float b = Vector2.Distance(position, point1);// position到点point1的距离
    float c = Vector2.Distance(position, point2);// position到point2点的距离
    if (c <= accuracy || b <= accuracy)
    {
    distance = 0;
    return distance;
    }
    if (a <= accuracy)
    {
    distance = b;
    return distance;
    }
    if (c * c >= a * a + b * b)
    {
    distance = b;
    return distance;
    }
    if (b * b >= a * a + c * c)
    {
    distance = c;
    return distance;
    }
    float p = (a + b + c) / 2;// 半周长
    float s = Mathf.Sqrt(p * (p - a) * (p - b) * (p - c));// 海伦公式求面积
    distance = 2 * s / a;// 返回点到线的距离(利用三角形面积公式求高)
    return distance;
    }

    相关文章

      网友评论

          本文标题:Unity 平面点到直线的距离

          本文链接:https://www.haomeiwen.com/subject/wpkigxtx.html