如何在矩形的周长中找到最接近给定点的点? [英] How to find the nearest point in the perimeter of a rectangle to a given point?
问题描述
这是一个与语言无关的问题.给定矩形的尺寸为l,t,w,h
(左,顶部,宽度,高度),并指定一个点x,y
,如何找到矩形周长上与该点最近的点?
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?
我试图用Lua解决它,但是任何其他语言都可以.到目前为止,这是我的最大努力:
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
这适用于周边的外部点或周边的点.但是对于外围的内部点,它会失败(它只会返回x,y
)
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.
推荐答案
这一次,我试图捕捉该点朝向矩形任意边的最小距离.
This time I'm trying to catch the minimum distance of the point toward any side of the rectangle.
local abs, min, max = math.abs, math.min, math.max
local function clamp(x, lower, upper)
return max(lower, min(upper, x))
end
local function getNearestPointInPerimeter(l,t,w,h, x,y)
local r, b = l+w, t+h
x, y = clamp(x, l, r), clamp(y, t, b)
local dl, dr, dt, db = abs(x-l), abs(x-r), abs(y-t), abs(y-b)
local m = min(dl, dr, dt, db)
if m == dt then return x, t end
if m == db then return x, b end
if m == dl then return l, y end
return r, y
end
这篇关于如何在矩形的周长中找到最接近给定点的点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!