Getting the points for the minimum distance between two parts

I need an efficient way to find the minimum distance between two (block) parts, and the pair of points that achieves this minimum distance. The method must also work for rotated parts.

This is basically a follow up to this question which I believe has an incorrectly marked answer and does not actually correctly calculate the minimum distance.

An example of why this is the case is shown in the picture below.
image

Any ideas for a proper solution?

1 Like

What you mean with “points”?

[30 chars]

The pair of vector3 values that give the minimum distance between the two parts.

In this case, if there is no rotation, then the minimum distance is simply the difference in either to X or Z value… plus or minus the part size however you want to do it…

Ah, that is a good point, I forgot to mention though that I need a solution for parts with any rotation so this does not work me.

I quickly looked at the solution in the thread you linked and noticed one thing.

The snippet posted was:

local p1 = ClosestPointOnPart(part1, part2.Position)
local p2 = ClosestPointOnPart(part2, part1.Position)
local minDistance = (p1 - p2).magnitude

But I think it should actually be:

local p1 = ClosestPointOnPart(part1, part2.Position)
local p2 = ClosestPointOnPart(part2, p1)
local minDistance = (p1 - p2).magnitude

After that small modification, it seemed to work fine when I tested it in studio.

EDIT: There may be some cases for where this does not work, I haven’t tested many pairs of rotations.

EDIT 2: I did find some counterexamples now.

local p1 = ClosestPointOnPart(workspace.Part1, workspace.Part2.Position)
local p2 = ClosestPointOnPart(workspace.Part2, p1)
	
local p3 = ClosestPointOnPart(workspace.Part2, workspace.Part1.Position)
local p4 = ClosestPointOnPart(workspace.Part1, p3)

In some cases p3 → p4 is shorter than p1 → p2, so the either the minimum distance is simply

math.min((p4 - p3).Magnitude, (p2 - p1).Magnitude)

or I am approaching the problem the wrong way. This is a little beyond me, apologies that I cannot concretely verify whether it truly works or not.

EDIT 3: Yeah, I’m approaching it the wrong way. Found a counterexample to both.

Yea, it’s certainly an improvement on what I had before, but still doesn’t find the minimum distance for some situations unfortunately.

image

Yep, I was able to see that later on. As for now, I’m all out of ideas.

I’ve managed to get this to work using this answer from stackoverflow, although the quadratic progrmaming solution on there may be better for efficiency.

image
Seems to work really well for me though and runs ok!

2 Likes