如何测量Unity3d中两个线段之间的距离

时间:2017-09-19 21:16:24

标签: c# math unity3d

我有4个向量指向一个正方形的4个角。我想检测它们是否与指向其他地方的另一个矢量有一定距离,如果是,则相应地采取行动。我发现一个算法据说是测量两个线段之间的最近距离,但我认为它不能正常工作:

public class Test : MonoBehaviour {
    public void FixedUpdate() {
        var source = new Vector3(0, 0, 0);
        var target = new Vector3(0, 0, 4);
        var otherSource = new Vector3(1.6f, 0, -0.5f);

        foreach (var dir in new[] {
            new Vector3(source.x + 1, source.y, source.z + 1),
            new Vector3(source.x - 1, source.y, source.z + 1),
            new Vector3(source.x + 1, source.y, source.z - 1),
            new Vector3(source.x - 1, source.y, source.z - 1)
        }) {
            var A = source;
            var B = otherSource;
            var a = dir - A;
            var b = target - B;

            var n = Vector3.Cross(a, b);
            var u = Vector3.Cross(n, A - B) / Vector3.Dot(n, n);

            var AA = A - a * Vector3.Dot(b, u);
            var BB = B - b * Vector3.Dot(a, u);

            Debug.DrawRay(A, a, Color.blue);
            Debug.DrawRay(B, b, Color.red);
            Debug.DrawLine(AA, BB, Color.green);
        }
    }
}

现在,如果你运行它,你会看到类似的东西:

enter image description here

我希望看到四条绿线,但没有。如果我向后移动otherSource向量,那么我会看到:

enter image description here

好一点,但仍然不是我想要的。有没有帮助调整这个算法?

1 个答案:

答案 0 :(得分:0)

所以我似乎误解了实际上必须做的事情。为了获得我需要的信息(点和光线之间的距离),我使用了这段代码:

public static float PointToRayDistance(Vector3 point, Vector3 origin, Vector3 target) {
    var ray = new Ray(origin, target - origin);
    var cross = Vector3.Cross(ray.direction, point - ray.origin);

    return cross.magnitude;
}

希望它会帮助别人。

我已经离开了原始问题的标题,因为我猜很多新手可能会使用相同的词来寻找我所做的相同的事情:)