What's the best way to find the closest position?

Hey I am trying to find the closest position from a table and I want to know what’s the best way.

Here’s an example:

local PositionsTable = {Vector3.new(0,0,1),Vector3.new(3,4,6),Vector3.new(5,5,4),Vector3.new(6,5,9)} -- Random Positions

local ObjectPosition = Vector3.new(0,2,0) -- The Position of the Object

local function GetClosest(ObjPos)
	local LastPos
	local LastMagnitude
	
	for _,CurrentPos in pairs(PositionsTable) do
		
		if LastMagnitude == nil or (ObjPos - CurrentPos).Magnitude < LastMagnitude then
			LastMagnitude = (ObjPos - CurrentPos).Magnitude
			LastPos = CurrentPos
		end
	end
	
	return LastPos
end

local ClosestPos = GetClosest(ObjectPosition)
1 Like

You can try using math.huge, however the only problem is that it would probably require all 3 numbers to compare between the vectors. I would assume.

local PositionsTable = {Vector3.new(0,0,1),Vector3.new(3,4,6),Vector3.new(5,5,4),Vector3.new(6,5,9)} -- Random Positions
local ObjectPosition = Vector3.new(0, 2, 0) -- The Position of the Object

local function GetClosest(ObjPos)
	local ClosestMag = math.huge
	local Closest = ObjPos 

	for _,CurrentPos in pairs(PositionsTable) do
		local ClosestVector = (CurrentPos - ObjPos).Magnitude
		if ClosestVector < ClosestMag then
			ClosestMag = (CurrentPos - ObjPos).Magnitude
			Closest = CurrentPos		
		end
	end
	print(Closest)
	return Closest
end

local ClosestPos = GetClosest(ObjectPosition)
1 Like