I need to write a function that returns the distance between two models. Any help?
✓ ANSWER ACCEPTED
Distance in 3 Dimensional space?
1 answer
✓ Accepted answer
local function findDistance(position1, position2) --Takes two Vector3 arguments
local X1 = position1.X; local X2 = position2.X;
local Y1 = position1.Y; local Y2 = position2.Y;
local Z1 = position1.Z; local Z2 = position2.Z;
return math.sqrt((X2-X1)^2+(Y2-Y1)^2+(Z2-Z1)^2)
end
Or you could have a function that works with both Vector2 and Vector3
local function findDistance(position1, position2)
local distance = 0;
if position1:IsA("Vector3") and position2:IsA("Vector3") then
local X1 = position1.X; local X2 = position2.X;
local Y1 = position1.Y; local Y2 = position2.Y;
local Z1 = position1.Z; local Z2 = position2.Z;
distance = math.sqrt((X2-X1)^2+(Y2-Y1)^2+(Z2-Z1)^2);
elseif position1:IsA("Vector2") and position2:IsA("Vector2") then
local X1 = position1.X; local X2 = position2.X;
local Y1 = position1.Y; local Y2 = position2.Y;
distance = math.sqrt((X2-X1)^2+(Y2-Y1)^2)
end
return distance;
end
This discussion is preserved as it was. New answers, comments, and votes are closed.

8 comments
Thanks, this is exactly what I needed!
For a much simpler to implement example: (position1 - position2).magnitude
It seems that most of the basic math is already built into Roblox. This function can be used as a base for other things though.
Omg, excellent answer! I'll be sure to use this in my scripts. Thanks!
Does this work with any Vector3 vlaue?
Yes, yes it does.
It only works with Vector3s is the only issue. .magnitude works for Vector2s as well.
It wouldn't be to hard to type test the arguments first then conditionally calculate.