Get point on a path or polyline which is closest to a disconnected point

后端 未结 2 1841
小鲜肉
小鲜肉 2020-12-09 13:40

I have a point and a path, polyline, or set of points to create lines.

How can I find the point on my path which closest to another disconnected point?

It\'

2条回答
  •  春和景丽
    2020-12-09 14:31

    Here is the algorithm that I've implemented as a solution. There's nothing 'non-obvious' in here if you've spent more than ten minutes thinking about it.

    I'll reference the distance algorithm which you can find here: https://stackoverflow.com/a/1501725/146077

    1. Collect the Polyline as a set of ordered lines
    2. Traverse this set, testing the distance from the target point to each line
    3. Once the closest line has been identified run the below to identify the closest point on the line.

    The answer linked above uses a projection to test if the point is closest to either end of the interval than any other point. I've modified the function from that answer to return the point's position on that projection. Beware that this answer might not make any sense if you haven't read the linked answer!

    private Point GetClosestPointOnLine(Point start, Point end, Point p)
    {
        var length = (start - end).LengthSquared;
    
        if (length == 0.0)
            return start; 
    
        // Consider the line extending the segment, parameterized as v + t (w - v).
        // We find projection of point p onto the line. 
        // It falls where t = [(p-v) . (w-v)] / |w-v|^2
        var t = (p - start) * (end - start) / length;
    
        if (t < 0.0)
            return start; // Beyond the 'v' end of the segment
        else if (t > 1.0)
            return end;   // Beyond the 'w' end of the segment
    
        // Projection falls on the segment
        var projection = start + t * (end - start);  
        return projection;
    }
    

提交回复
热议问题