Checking if a point is inside or outside of a polygon

When checking collisions in 2D projections between a point and a polygon, it is necessary to find out whether the point lies inside the polygon, or whether it is located outside its area.

As an example, let’s create a curvilinear polygon (n-gon) of any shape called “Plane” and a separate mesh called “Point”, consisting of just one vertex.

We can get the polygon and the point object as follows:

To determine whether the point lies inside the polygon, we will use the following algorithm:

  • Loop sequentially along all the edges of the polygon;
  • For each edge of the polygon, check whether the point lies to the left or to the right of it;
  • If, as a result of all checks, the point lies to the right of the edges an even number of times, the point is inside the polygon;
  • If the point lies to the right of the edges an odd number of times, the point is outside the polygon;
  • If the point lies on one of the edges, it immediately considers that the point is inside the polygon.

Let’s see how this algorithm works for projection onto the XY plane.

First, we need to get the coordinates of all points of the polygon in sequential order. We can use the points_sorted() function for this.

Coordinates of our single point:

If the origins of the polygon and the point being checked do not lie in the center of coordinates (0.0, 0.0, 0.0), we need to additionally bring all coordinates to the global coordinate system – multiply by the world “matrix_world” matrix.

Now let’s define a function that in the parameters will receive a list of polygon point coordinates sorted in the desired order and the single point coordinates, and return 1 if the point is inside the polygon, or 0 if it lies outside the polygon.

Now we can call our function and pass the previously obtained data with the coordinates of the points of the polygon and the single point to be checked to it:

In our example, the point lies outside the polygon. You can move it to any other place (in the Edit mode, if the coordinates are not converted to the global system) and check again.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comment
Inline Feedbacks
View all comments