Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Point on Line-Segment Distance Away from a Point

I am looking for an algorithm (or the name of the algorithm) that will find a point on a line-segment, if such a point exists, that is some given distance away from another point that not on the line-segment.

i.e., There exist, three points A, B, C; and possibly a fourth D. Where AB makes up a line-segment, and point C is another point somewhere OFF of the line-segment AB. Find a point D, if such point exists, that appears on the line-segment AB that is a given distance distance away from point C.

like image 368
Ryan Avatar asked Dec 16 '22 19:12

Ryan


2 Answers

Look here: Circle-Line Intersection

C is the circles middle and distance is the radius.

Note that there may be two resulting points and that you have to check whether the point is actually on your line (or on the line that you would get by extending it).

like image 146
thejh Avatar answered Jan 13 '23 03:01

thejh


I spent WAY too long figuring this out and couldn't seem to find a simple answer anywhere, so I figured I'd post it here and save some people a lot of time. Even though the original posting is old, I sure wish somebody had posted a simple answer long ago. It would have saved me a couple days of experimenting.

public static Point PointFromEndOfLine(Point start, Point end, double distance)
{
    double x = end.X-start.X;   
    double y = end.Y-start.Y;
    double z = Math.Sqrt(x * x + y * y);  //Pathagrean Theorum for Hypotenuse
    double ratio = distance / z;
    double deltaX = x * ratio;
    double deltaY = y * ratio;

    return new Point(end.X-deltaX, end.Y-deltaY);
}

The function above takes a startPoint (x,y) and an endPoint (x,y) and a distance (from the endpoint. If your distance is negative, the returned point will be beyond the endPoint along the same line. If your distance is greater than the distance between startPoint and endPoint, the return point will be before your startpoint, but still on the same line. If your distance is a positive number and is less than the distance between startPoint and endPoint, the point returned will be on the line segment between the startPoint and endPoint at 'distance' from the endpoint.

The reason it works is 'Similar Triangles'. Imagine a large right triangle. Draw a strait line through the triangle parallel to the X axis and the x,y,z values of your big triangle and the smaller one created by the line you drew will be proportional to each other.

In other words: x/X == y/Y == z/Z

Hope this helps somebody out.

like image 29
Curtis Avatar answered Jan 13 '23 02:01

Curtis