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?