Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I find the difference (length) between 2 objects?

Asked by 10 years ago

I'm not sure if this question has been asked before, but How would I calculate, using a script, the difference between Part A and Part B??

2 answers

Log in to vote
1
Answered by 10 years ago
parta = Workspace.PartA
partb = Workspace.PartB

distance = (parta.Position-partb.Position).magnitude
print(distance)
Ad
Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

What exactly you mean by "distance between parts" is first what you need to determine.

The simple solution, which for small parts is more than good enough, is to consider the distance from center of A to center of B.

The center of a part is its Position. Since they are vectors, we subtract them to find the vector from A to B; that vector's length is called its magnitude.

local distanceBetweenCenters = (A.Position - B.Position).magnitude;

While the above is probably what you want, it also might not be. Maybe you want the distance between the part's edges (the length of the gap)

Doing this precisely is very difficult, but if for instance you were using spheres, you just subtract the radius of the spheres from the above distance:

local radiusA = (A.Size.x + A.Size.y + A.Size.z) / 2 / 3;
local radiusB = (B.Size.x + B.Size.y + B.Size.z) / 2 / 3;
local distanceBetweenSurfaces =
    distanceBetweenCenters - radiusA - radiusB;

However, this only works well with cubes and spheres.

In some cases, like with a large, flat base plate, neither of these is sufficient. We instead could compare coordinates: math.abs(baseplate.Position.y - A.Position.y), however, if we tilt the baseplate, then this would be inaccurate.

Answer this question