Approach Overview
The figure illustrates the functioning of the Ray Casting Algorithm in determining whether a point lies within a polygon.
To determine if the point lies within the polygon, simply create a ray extending from the given point in any direction. Then, count the total number of intersections between the ray and the polygon boundary. If it is odd, the point is inside the polygon.
In this way, as the figure illustrate:
The ray starting from P1 does not intersect with the polygon boundary, indicating that P1 is located outside the polygon.
The ray originating from P2 intersects the boundary twice, yielding an even count, which indicates that P2 is situated outside the polygon.
Conversely, the ray originating from P3 intersects the boundary only once, resulting in an odd count, indicating that P3 lies inside the polygon.
Code
Here is a piece of Python code script to implement this approach.
1 | # coding: utf-8 |