• Advertisement
Sign in to follow this  

Line/Line-Segment intersection in 2D

This topic is 3674 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I know how to find the intersection of two lines, but how do I ensure that the intersection point lies on the segment? The only way I can see to do it, is to plug the inersection point into the ray equation defined by the segment and then solve for the parameter and check that way. Is there a faster way than this? Thanks, s.

Share this post


Link to post
Share on other sites
Advertisement

That should be simple enough. your line / line intersection should return two parametric value, one for each lines. Then it's simply a matter of checking if those parameters are within the segment parametric boundaries (either in range [0, 1] or [0, segment length]). But it depends how you perform your line / line test.

What's your line / line intersection doing exactly?

Share this post


Link to post
Share on other sites
I figured it out. I was getting strange results because I was feeding it incorrect data. Oops. Anyway, here is the code, just in case anybody is wondering:



bool line_segment_intersection(const vec2f& a, const vec2f& b, //line
const vec2f& c, const vec2f& d, //segment
vec2f& result) {

//test for parallel case
float denom = (d.y - c.y)*(b.x - a.x) - (d.x - c.x)*(b.y - a.y);
if(abs(denom) < epsilon)
return false;

//calculate segment parameter and ensure its within bounds
float t = ((b.x - a.x)*(a.y - c.y) - (b.y - a.y)*(a.x - c.x))/denom;
if(t < 0.0f || t > 1.0f)
return false;

//store actual intersection
result = c + (d - c)*t;
return true;

}


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement