Polygon Hit Test with Ray Casting

Another old project that I’ve been digging back into with JavaScript recently has been the Lassie engine’s geometry system. Now, first and foremost, that’s NOT to say that the Lassie engine is in production for HTML5 (coding in my free time is not among my current priorities!). However, I’ve always found Lassie’s point-and-rectangle grid system to be archaic, and in all honesty, the only reason for that is because I’ve never taken the time to figure out polygon math. So, I’ve been tinkering with this…

The first thing that Lassie’s grid system would need to support polygons is a way to hit-test points against a polygonal area. A quick Google search on this led to an old (and shockingly simple) technique called ray casting.

The premise of ray casting involves extending a ray in one direction from the target point, and then counting how many times that ray intersects sides of the polygon in question. If the intersection count is an even number, then we can assume that the ray has both entered and exited the polygon’s boundaries an equal number of times, therefore placing the point outside of the polygon. However, if the intersection count is an odd number, then the point has entered but never left the bounds of the polygon and is therefore inside. Amazing that such a simple test holds up.

You’ll see our test uses three methods. First, ccw() tests for counter-clockwise winding among three points. Using that, we can test intersection() between two line segments by testing if the points of either segment wind into one another. Finally, we can perform ray casting by testing a target point’s line to an exterior point against each line segment in the polygon, and counting the number of intersections that are registered. Keep in mind that point order of your polygon array does matter (although the hit test still seems to work for oddly-wound polygons with intersecting sides). To see the hit test in action, try this: