# Line/Line-Segment intersection in 2D

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

## 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 on other sites

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 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;

}

1. 1
Rutin
49
2. 2
3. 3
4. 4
5. 5

• 11
• 16
• 9
• 10
• 13
• ### Forum Statistics

• Total Topics
633003
• Total Posts
3009846
• ### Who's Online (See full list)

There are no registered users currently online

×