Intersection between two lines as defined by points without extending lines

不问归期 提交于 2020-01-25 06:30:06

问题


I know there are various posts on stackoverflow about given two lines defined by two points each, being able to calculate the intersection, but typically those solutions extend the lines as opposed to treating their physical sizes.

Background search: The typical function used to calculate the intersection of two lines as defined by points is shown below, but credit goes to here.

// Finds the intersection of two lines, or returns false.
// The lines are defined by (o1, p1) and (o2, p2).
bool intersection(Point2f o1, Point2f p1, Point2f o2, Point2f p2,
                  Point2f &r)
{
Point2f x = o2 - o1;
Point2f d1 = p1 - o1;
Point2f d2 = p2 - o2;

float cross = d1.x*d2.y - d1.y*d2.x;
if (abs(cross) < /*EPS*/1e-8)
    return false;

double t1 = (x.x * d2.y - x.y * d2.x)/cross;
r = o1 + d1 * t1;
return true;
}

Problem: While this code works phenomenally, I am wondering if anyone knows how to alter this function where if the lines as defined by the points do not physically intersect. Currently, the lines ultimately get extended.

ex: o1 = 0,0 p1 = 10,0 o2 = 5,5 p2 = 5,-5 Naturally, this would intersect at 5,0.

ex: o1 = 0,0 p1 = 10,0 o2 = 5,5 p2 = 5,2 While the function also says this intersection is at 5,0, lines defined by the points however do not physically intersect, so in this case I'd want the function to return false.

I've considered modifying this function to at the end, check if r is between the two points for each line and came across the suggested formula of here.. I'm wondering if there might be a better or easier solution?

来源:https://stackoverflow.com/questions/25852531/intersection-between-two-lines-as-defined-by-points-without-extending-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!