Shortest distance between two line segments

2019-01-14 08:21发布

I need a function to find the shortest distance between two line segments. A line segment is defined by two endpoints. So for example one of my line segments (AB) would be defined by the two points A (x1,y1) and B (x2,y2) and the other (CD) would be defined by the two points C (x1,y1) and D (x2,y2).

Feel free to write the solution in any language you want and I can translate it into javascript. Please keep in mind my geometry skills are pretty rusty. I have already seen here and I am not sure how to translate this into a function. Thank you so much for help.

9条回答
我想做一个坏孩纸
2楼-- · 2019-01-14 08:44

Is this in 2 dimensions? If so, the answer is simply the shortest of the distance between point A and line segment CD, B and CD, C and AB or D and AB. So it's a fairly simple "distance between point and line" calculation (if the distances are all the same, then the lines are parallel).

This site explains the algorithm for distance between a point and a line pretty well.

It's slightly more tricky in the 3 dimensions because the lines are not necessarily in the same plane, but that doesn't seem to be the case here?

查看更多
Explosion°爆炸
3楼-- · 2019-01-14 08:45

All 2D lines unless they are parallel will eventually meet. Learn what is being taught so you understand it rather than trying to cheat this particular q.

查看更多
登录 后发表回答