Search code examples
luaintersectionsegment

Ray to Line Segment Intersection


I am having trouble with ray to line segment intersections. I am coding in Lua, but examples in any language would be useful as well.

I have spent most of this week looking for algorithms or existing functions that I could base mine off of, and I came across this the other day:

bool RayLineSegmentIntersection( const vec2 &o, const vec2 &d, const vec2 &a, const vec2 &b )
{
    vec2 ortho( -d.y, d.x );
    vec2 aToO( o - a );
    vec2 aToB( b - a );

    float denom = dot( aToB, ortho );

    // Here would be a good time to see if denom is zero in which case the line segment and
    // the ray are parallel.

    // The length of this cross product can also be written as aToB.x * aToO.y - aToO.x * aToB.y.
    float t1 = length( cross( aToB, aToO ) ) / denom;
    float t2 = dot( aToO, ortho ) / denom;

    return t2 >= 0 && t2 <= 1 && t1 >= 0;
}

Source

However, I am not sure what the author means by the length, as the comment simply defines the cross product, and there is no defined function length.

My implementation is similar, but since I do not know what he means by length, I simply take the cross product there. The problem is that the line segments seem to be treated as rays, because I am getting intersections that should not be possible unless I am intersecting rays. For example, a ray going straight through the center of a rectangle is reporting intersections through other rectangles (I loop through lines for now) that it should not be intersecting.

Are there better ways to go about this, or is the missing length function above what would fix this issue?

Here is a crude drawing of what I expect to happen, and what I think is happening:

Drawing


Solution

  • It turns out that the issue was not the algorithm, but an error elsewhere in my code. It took me a while to figure it out, but once I did the algorithm works perfectly.