How can I determine whether a 2D Point is within a Polygon?

前端 未结 30 2151
醉梦人生
醉梦人生 2020-11-21 05:06

I\'m trying to create a fast 2D point inside polygon algorithm, for use in hit-testing (e.g. Polygon.contains(p:Point)). Suggestions for effective tech

30条回答
  •  花落未央
    2020-11-21 06:04

    I've made a Python implementation of nirg's c++ code:

    Inputs

    • bounding_points: nodes that make up the polygon.
    • bounding_box_positions: candidate points to filter. (In my implementation created from the bounding box.

      (The inputs are lists of tuples in the format: [(xcord, ycord), ...])

    Returns

    • All the points that are inside the polygon.
    def polygon_ray_casting(self, bounding_points, bounding_box_positions):
        # Arrays containing the x- and y-coordinates of the polygon's vertices.
        vertx = [point[0] for point in bounding_points]
        verty = [point[1] for point in bounding_points]
        # Number of vertices in the polygon
        nvert = len(bounding_points)
        # Points that are inside
        points_inside = []
    
        # For every candidate position within the bounding box
        for idx, pos in enumerate(bounding_box_positions):
            testx, testy = (pos[0], pos[1])
            c = 0
            for i in range(0, nvert):
                j = i - 1 if i != 0 else nvert - 1
                if( ((verty[i] > testy ) != (verty[j] > testy))   and
                        (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]) ):
                    c += 1
            # If odd, that means that we are inside the polygon
            if c % 2 == 1: 
                points_inside.append(pos)
    
    
        return points_inside
    

    Again, the idea is taken from here

提交回复
热议问题