Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check for intersection between a line segment and a line ray emanating from a point at an angle from horizontal?

Tags:

Given a line segment, that is two points (x1,y1) and (x2,y2), one point P(x,y) and an angle theta. How do we find if this line segment and the line ray that emanates from P at an angle theta from horizontal intersects or not? If they do intersect, how to find the point of intersection?

like image 928
Paagalpan Avatar asked Jan 13 '13 19:01

Paagalpan


People also ask

How do you detect where two line segments intersect?

Define b = q1 - p1 and x = (s,t). If the solution of the linear system A*x = b is in the unit square, then the segments intersect. If the solution is not in the unit square, the segments do not intersect.

How do you check if a ray intersects a line?

The two lines intersect if we can find t and u such that p + t r = q + u s: See this answer for how to find this point (or determine that there is no such point). Then your line segment intersects the ray if 0 ≤ t and 0 ≤ u ≤ 1.

What is the intersection of a ray and a line segment?

For lines, rays, and line segments, intersect means to meet or cross. When two lines, rays, or line segments intersect, they have one common point.


2 Answers

Let's label the points q = (x1, y1) and q + s = (x2, y2). Hence s = (x2x1, y2y1). Then the problem looks like this:

Let r = (cos θ, sin θ). Then any point on the ray through p is representable as p + t r (for a scalar parameter 0 ≤ t) and any point on the line segment is representable as q + u s (for a scalar parameter 0 ≤ u ≤ 1).

The two lines intersect if we can find t and u such that p + t r = q + u s:

See this answer for how to find this point (or determine that there is no such point).

Then your line segment intersects the ray if 0 ≤ t and 0 ≤ u ≤ 1.

like image 133
Gareth Rees Avatar answered Sep 20 '22 02:09

Gareth Rees


Here is a C# code for the algorithm given in other answers:

    /// <summary>     /// Returns the distance from the ray origin to the intersection point or null if there is no intersection.     /// </summary>     public double? GetRayToLineSegmentIntersection(Point rayOrigin, Vector rayDirection, Point point1, Point point2)     {         var v1 = rayOrigin - point1;         var v2 = point2 - point1;         var v3 = new Vector(-rayDirection.Y, rayDirection.X);           var dot = v2 * v3;         if (Math.Abs(dot) < 0.000001)             return null;          var t1 = Vector.CrossProduct(v2, v1) / dot;         var t2 = (v1 * v3) / dot;          if (t1 >= 0.0 && (t2 >= 0.0 && t2 <= 1.0))             return t1;          return null;     } 
like image 28
ezolotko Avatar answered Sep 21 '22 02:09

ezolotko