How to check if a line segment intersects with a polygon?

As you are using v9, I would suggest using the undocumented function - Graphics`Mesh`IntersectQ which does exactly what you want:

plist = {Line[{{20, 10}, {20, 0}}], Polygon[list]};
Graphics`Mesh`IntersectQ[plist]
Graphics[MapThread[{##} &, {{Red, Blue}, plist}]]
(* False *)

enter image description here

which is also in v10.


In v10 this is a one-liner:

RegionDimension@RegionIntersection[Line[{{0, 10}, {20, 0}}], Polygon[list]]] > -∞

because an empty region has dimension $-\infty$. I do wish there was a NonemptyQ predicate one could use directly, though.


A "solution" using v10 would be: RegionQ@DiscretizeRegion@RegionIntersection[r1, r2].

For example:

r1 = Line[{{0, 10}, {20, 0}}];
r2 = Polygon[{{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {9.5, 14.9}, {13.2, 11.9},
              {10.3, 12.3}, {6.8, 9.5}, {13.3, 7.7}, {0.6,1.1}, {1.3, 2.4}, {2.45, 4.7}}];
g = Show[Graphics[{r1, r2}]];
ri = DiscretizeRegion@RegionIntersection[r1, r2];
RegionQ@ri
True

With r1 = Line[{{0, 10}, {-20, 0}}]; one will have False.

Showing the intersection if it exists:

If[RegionQ@ri, 
  Show[
    DiscretizeRegion /@ {r1, r2},
    HighlightMesh[DiscretizeRegion[ri], Style[#, Red] & /@ {0, 1}]],
  g]

will give the following figures for {20, 0} and {-20, 0}:

Mathematica graphics

Mathematica graphics


With r1 = Line[{{10, 10}, {12, 10}}]:

False

Mathematica graphics


Side note (aka bug?):

Can someone please confirm this?

RegionQ[DiscretizeRegion@ RegionIntersection[#, r2]] & /@ 
  {Line[{{5, 10}, {12, 10}}], Line[{{5, 10.1}, {12, 10}}]}

DiscretizeRegion::drf: DiscretizeRegion was unable to discretize the region RegionIntersection[<<2>>]. >>

{False, True}

While it does intersect with Line[{{5, 10}, {12, 10}}]:

Mathematica graphics