is there a easy formula to calculate this? i\'ve been working on some math but i can only find a way to calculate the distance directed to the center of the box, not direct
Kikito's answer is not correct, in fact if P is in the regions 2, 4, 5 or 7 of Ted Hopp's scheme, it returns the minimum distance from the vertices, which is different (bigger) from the minimum distance from the edges.
I would fix kikito's function distance_aux by returning 0 instead of min(p - lower, upper - p), and everything works apart from the 0 region where P is inside the box. In my opinion that region should be managed separately, depending on what you want to achieve, whether the distance from the area or the distance from the perimeter of the box. If you want to obtain the distance from the area of the box, I would say that it is zero when the point is inside the box.
function inside(point, box)
return (point.x > box.left AND point.x < box.right AND point.y > box.top AND point.y < box.bottom)
end
function distance_aux(p, lower, upper)
if p < lower then return lower - p end
if p > upper then return p - upper end
return 0
end
function distance(point, box)
local dx = distance_aux(point.x, box.left, box.right)
local dy = distance_aux(point.y, box.top, box.bottom)
if (inside(point, box))
return min(dx, dy) // or 0 in case of distance from the area
else
return sqrt(dx * dx + dy * dy)
endif
end