This is a language-agnostic question. Given a rectangle's dimensions with l,t,w,h
(left, top, width, height) and a point x,y
, how do I find the nearest point on the perimeter of the rectangle to that point?
I have tried to resolve it in Lua, but any other language would do. So far this is my best effort:
local function nearest(x, a, b)
if a <= x and x <= b then
return x
elseif math.abs(a - x) < math.abs(b - x) then
return a
else
return b
end
end
local function getNearestPointInPerimeter(l,t,w,h, x,y)
return nearest(x, l, l+w), nearest(y, t, t+h)
end
This works for a point outside of the perimeter or in the perimeter itself. But for points inside of the perimeter it fails (it just returns x,y
)
My gut tells me that the solution should be simple, but I don't seem to find it.