'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.

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)?

I am doing the following given the distance_to_travel and points 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))


Solution 1:[1]

You should find the slope of the line between a and 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).

Now you can convert from spherical to Cartesian to find x, y coordinates of new point. Then you add this values to values of point 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)

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MSH
Solution 2 Joffan