nearest

Useful functions to find the nearest.

Nearest point in array of points

-- function to calculate the distance between two points
local function distance(x1, y1, x2, y2)
	return math.sqrt((x2 - x1)^2 + (y2 - y1)^2)
end

-- function to find the nearest point from a list of points
function findNearestPointInPoints (points, point)
-- points is array of pairs: {x1, y1, x2, y2, ...}
	local minDistance = math.huge
	local nearestX, nearestY = nil, nil
	for i = 1, #points, 2 do
		local x, y = points[i], points[i + 1]
		local dist = distance(x, y, point[1], point[2])
		if dist < minDistance then
			minDistance = dist
			nearestX, nearestY = x, y
		end
	end
	return nearestX, nearestY, minDistance
end