[英]Given two coordinates, a and b, how do I find a point that is x distance from a heading towards b?
I am working on a python script and I am sure there is an easier way to approach this problem then my solution so far.我正在处理一个 python 脚本,我确信有一种比我目前的解决方案更简单的方法来解决这个问题。
Give two coordinates, say (0,0) and (40,40) and a set distance to travel, say 5, how would I find a new coordinate pair for the point that is 5 units from (0,0) heading along the line that connects (0,0) and (40,40)?给定两个坐标,比如 (0,0) 和 (40,40) 以及设定的行进距离,比如 5,我如何为距离 (0,0) 方向 5 个单位的点找到一个新的坐标对连接 (0,0) 和 (40,40) 的线?
I am doing the following given the distance_to_travel and points p0, p1:给定 distance_to_travel 和点 p0、p1,我正在执行以下操作:
ang = math.atan2(p1.y - p0.y, p1.x - p0.x)
xx = node0.x + (distance_to_travel * math.cos(ang))
yy = node0.y + (distance_to_travel * math.sin(ang))
Following the method outlined in my comment:按照我的评论中概述的方法:
# find the vector a-b
ab.x, ab.y = p1.x - p0.x, p1.y - p0.y
# find the length of this vector
len_ab = (ab.x * ab.x + ab.y * ab.y) ** 0.5
# scale to length 5
ab5.x, ab5.y = ab.x *5 / len_ab, ab.y *5 / len_ab
# add to a (== p0)
fin.x, fin.y = p0.x + ab5.x, p0.y + ab5.y
You should find the slope of the line between a and b |ab|
你应该找到 a 和 b
|ab|
之间的线的斜率. .
Then you can use 2D spherical (polar) coordinate system to get r
mount of distance with a given slope (The slope you found earlier).然后,您可以使用 2D 球面(极)坐标系获得具有给定斜率(您之前找到的斜率)的
r
距离。
Now you can convert from spherical to Cartesian to find x, y coordinates of new point.现在您可以将球面坐标转换为笛卡尔坐标,以找到新点的 x、y 坐标。 Then you add this values to values of point a:
然后将此值添加到点 a 的值:
import math
def slope(p1, p2):
return math.atan2(
(p2[1] - p1[1]), (p2[0] - p1[0])
)
def spherical_to_cartesian(r, theta):
x = r * math.cos(theta)
y = r * math.sin(theta)
return x, y
def add_points(p1, p2):
return p1[0] + p2[0], p1[1] + p2[1]
if __name__ == '__main__':
a = [0, 0]
b = [40, 40]
slp = slope(a, b)
r = 5
new_p = spherical_to_cartesian(r, slp)
res = add_points(a, new_p)
print(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.