Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Distance in 3 Dimensional space?

I need to write a function that returns the distance between two models. Any help?

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

8 comments

0

Thanks, this is exactly what I needed!

0

For a much simpler to implement example: (position1 - position2).magnitude

0

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.

0

Omg, excellent answer! I'll be sure to use this in my scripts. Thanks!

0

Does this work with any Vector3 vlaue?

0

Yes, yes it does.

0

It only works with Vector3s is the only issue. .magnitude works for Vector2s as well.

0

It wouldn't be to hard to type test the arguments first then conditionally calculate.

This discussion is preserved as it was. New answers, comments, and votes are closed.