Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Point inside a polygon?

Given a list of points that represent the polygon in 2D, how can I determine if the point is inside the polygon.

Please note that the polygon can be either concave or convex. You can also make any assumptions about the order of the points.

like image 712
iBrAaAa Avatar asked Dec 27 '22 12:12

iBrAaAa


1 Answers

The best approach to doing this is to draw a line in any direction from your point, and count the number of times that you cross the boundary of the object. If you hit the boundary an even number of times, you are outside the object, if an odd, you are inside. It is usually easiest to go along one of the axis to make this determination.

Essentially, you just have to find a way to determine if you cross a point. Use the slope of a line equation(m=(y1-y2)/(x1-x2), y=m*x(x-x1)+y1, and see if you cross within the boundaries that the point is valid. Given this equation for the line between the points, determine where your line crosses this line, and figure out if it is within the range of the line.

Incidentally, the same method works for any arbitrary dimension, just determining if you hit the face becomes more difficult.

To show a couple of examples, I've drawn a simple illustration, showing both what happens inside and outside, even with a weird shape.

Incidentally, if you hit a corner, it counts for the number of times you make a transition from inside to outside.

enter image description here

like image 59
PearsonArtPhoto Avatar answered Dec 29 '22 00:12

PearsonArtPhoto