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?
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.
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.
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.
Let's label the points q = (x1, y1) and q + s = (x2, y2). Hence s = (x2 − x1, y2 − y1). 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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With