该函数应该接受一个点参数,该参数将用于找到位于线段对象上的最近点。在这个例子中断言代码的功能getClosestPoint(Point())需要Point(10, 0)的参数,而应返回Point(5,5)的最近点Point(10, 0) 是上线l1 = Line(Point(5,5), Point(20,35))与端点是A Point(5,5), B Point(20,35)我不知道如何去解决这个问题。我当前的解决方案将返回 (4,3) 并且不在线段上,而是在线上。
from point import Point
import math
class Line:
def __init__(self,aPoint=Point(), bPoint=Point()):
self.firstPoint = aPoint
self.secondPoint = bPoint
def getClosestPoint(self,point=Point()):
m1 = self.getSlope()
m2 = -1 / float(m1)
b1 = self.p1.y - m1 * self.p1.x
b2 = point.y - m2 * point.x
x = float(b2 - b1) / float(m1 - m2)
y = m1 * x + b1
return Point(x, y)
if __name__ == "__main__":
p1 = Point(5,5)
p2 = Point(20,35)
l1 = Line(p1,p2)
assert l1.getClosestPoint(Point(10,0)) == Point(5,5)
assert l2.getClosestPoint(Point(25/2,25/2)
class Point:
def __init__(self,x=0,y=0):
self.x = x
self.y = y
Run Code Online (Sandbox Code Playgroud)
一般的答案是将点投影到线上。查看它的一种方法是将点转换为由您的线段定义的参考系(p1是新的原点(0, 0),p2新的(1, 0))。然后,您摆脱新y坐标(即实际投影发生的位置)并将新点转换(x, 0)回原始帧。
具体来说,您必须找到转换。第二个,从新空间到原空间的写法很简单(画在纸上就知道了):
x = (x2 - x1) * nx + (y2 - y1) * ny + x1
y = (y1 - y2) * nx + (x2 - x1) * ny + y1
Run Code Online (Sandbox Code Playgroud)
但是你可以反转这些方程来找到(nx, ny)对应于一个点的(x, y)。
当你这样做时,假设我们都没有犯任何错误或打字错误,你应该得到类似的结果:
dx = x2 - x1
dy = y2 - y1
d2 = dx*dx + dy*dy
nx = ((x3-x1)*dx + (y3-y1)*dy) / d2
return (dx*nx + x1, dy*nx + y1)
Run Code Online (Sandbox Code Playgroud)
编辑:如果您实际上必须在该段而不是线上找到最近的点,则很容易找到,因为如果投影落在该段内,则您有0 <= nx <= 1(这是必要和充分条件)。在 return 语句之前,你可以强制nx停留在这个区间:
nx = min(1, max(0, nx))
Run Code Online (Sandbox Code Playgroud)
重新编辑:上面的语句等效于:
if nx<0:
nx = 0
if nx>1:
nx = 1
Run Code Online (Sandbox Code Playgroud)
这样,直线上的点(可以在段外)的投影0 <= nx <= 1在最近点处被推回到段内(由 定义)。