简体   繁体   中英

How to measure the distance between two line segments in Unity3d

I have 4 vectors pointing to 4 corners of a square. I'd like to detect if they are in a certain proximity to another vector pointing somewhere else and if so, act accordingly. I found an algorithm said to be measuring closest distance between two line segments, but it's not working properly I think:

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);
        }
    }
}

Now, if you run it, you'll see something like this:

在此处输入图片说明

I was hoping to see four green lines, but there are none. If I hovewer move the otherSource vector a bit up, then I see this:

在此处输入图片说明

So a bit better, but still not what I'm looking for. Any help adjusting this algorithm?

So it seems I misunderstood what actually had to be done. To get the info I needed (the distance between a point and a ray) I used this code:

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;
}

Hopefully it will help someone.

I'm leaving the original question's title, because I guess a lot of newbies may look for the same stuff I did, using the same words :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM