gpt4 book ai didi

c# - 获得离直线最近的点

转载 作者:IT王子 更新时间:2023-10-29 04:10:08 26 4
gpt4 key购买 nike

我想要一个直接的 C# 函数来获得最近点(从点 P)到线段 AB。一个抽象函数可能看起来像这样。我搜索过 SO 但没有找到可用的(对我来说)解决方案。

public Point getClosestPointFromLine(Point A, Point B, Point P);

最佳答案

这是伪装成伪代码的 Ruby,假设每个 Point 对象都有一个 xy 字段。

def GetClosestPoint(A, B, P)

a_to_p = [P.x - A.x, P.y - A.y] # Storing vector A->P
a_to_b = [B.x - A.x, B.y - A.y] # Storing vector A->B

atb2 = a_to_b[0]**2 + a_to_b[1]**2 # **2 means "squared"
# Basically finding the squared magnitude
# of a_to_b

atp_dot_atb = a_to_p[0]*a_to_b[0] + a_to_p[1]*a_to_b[1]
# The dot product of a_to_p and a_to_b

t = atp_dot_atb / atb2 # The normalized "distance" from a to
# your closest point

return Point.new( :x => A.x + a_to_b[0]*t,
:y => A.y + a_to_b[1]*t )
# Add the distance to A, moving
# towards B

end

或者:

来自 Line-Line Intersection , 在维基百科。首先,找到Q,这是从P向“正确的方向”迈出一步的第二个点。这给了我们四点。

def getClosestPointFromLine(A, B, P)

a_to_b = [B.x - A.x, B.y - A.y] # Finding the vector from A to B
This step can be combined with the next
perpendicular = [ -a_to_b[1], a_to_b[0] ]
# The vector perpendicular to a_to_b;
This step can also be combined with the next

Q = Point.new(:x => P.x + perpendicular[0], :y => P.y + perpendicular[1])
# Finding Q, the point "in the right direction"
# If you want a mess, you can also combine this
# with the next step.

return Point.new (:x => ((A.x*B.y - A.y*B.x)*(P.x - Q.x) - (A.x-B.x)*(P.x*Q.y - P.y*Q.x)) / ((A.x - B.x)*(P.y-Q.y) - (A.y - B.y)*(P.y-Q.y)),
:y => ((A.x*B.y - A.y*B.x)*(P.y - Q.y) - (A.y-B.y)*(P.x*Q.y - P.y*Q.x)) / ((A.x - B.x)*(P.y-Q.y) - (A.y - B.y)*(P.y-Q.y)) )

end

出于性能原因,缓存、跳过步骤等是可能的。

关于c# - 获得离直线最近的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3120357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com