简体   繁体   中英

Determine if point is inside polygon

Currently I am using the ray casting algorithm, however it has some limitations like when the ray passes a vertex it's impossible to determine whether it's inside or not.

What algorithm can I use that will always work in any kind of polygon?

You can select ray direction depending on polygon itself so that it doesn't cross any vertex.

For integer coordinates it would be enough to cast a ray along (1,0.5/deltaX) , where deltaX is the maximum difference between x-coordinates of polygon vertices. The first point with integer coordinates on the ray will be its start. The next one will have x-coordinate startX+2*deltaX which is outside of the polygon and cannot be its vertex. With exact arithmetic you can robustly determine whether the point inside or outside.

For floating point numbers exact arithmetic is a problem, so you want the ray to be as far from polygon vertices as possible. For this you can calculate direction to every polygon vertex atan2(y[n]-y,x[n]-x) and sort the vertices by it. Then select the biggest difference between neighbor vertices in this sorted sequence and cast the ray between them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM