- Home /
Programatically check whether a grid is placed inside or outside a closed figure
Hi everyone, I want to build an application with the functionality
1-Draw a closed figure eg:
2-Place a grid inside or outside eg:
where a-Grid inside the closed figure and b-Grid outside the closed figure
3-programatically check whether the grid a is inside or outside the closed figure
you may want check out PolygonCollider2D and OverlapPoint.
They common solution for checking if a point is inside or outside a closed figure is to walk each segment of the polyline that encloses the figure. For each segment, check to see what side (left or right) of the line formed by the segment the point is on. If the point is on the same side for all segments, then it is inside the polygon. For a rectangle, you'd have to check all four points and there are some degenerate cases with figure like #6 where all four points could be considered inside but part of the figure would be outside.
Like @robertbu points out, case 6 is the hard one here. You can do something like this to check if a point (corners of the rectangle) is inside a convex shape like 6, but even that doesn't work if one of the convex corners of shape 6 would go in to the checked rectangle through its side and out the same side: all corners would be inside but a side breaks the shape.
Raycasting or winding algorithms should still work with concave polygons, but you'll need to test all four corners of the rectangle from all segments that define the containing polyline, which might be slow depending on how complex the shapes are.
You might also be able to take some shortcuts by defining $$anonymous$$imum bounding rectangles of each shape and doing an initial test against those - we'd need to know more about the potential bounds of the grid and shape though.