DarkRewar / BaseTool

A big library of basic tools that you might need in your Unity projects.
MIT License
41 stars 6 forks source link

Add a `IsPointInPolygon` method #108

Open DarkRewar opened 4 weeks ago

DarkRewar commented 4 weeks ago

Proposal

Following this post, add a IsPointInPolygon method to check if a point is inside a polygon (which is a list of vectors).

public bool IsPointInPolygon(Vector2 point, Vector2[] polygon) {
   int polygonLength = polygon.Length, i=0;
   bool inside = false;
   // x, y for tested point.
   float pointX = point.x, pointY = point.y;
   // start / end point for the current polygon segment.
   float startX, startY, endX, endY;
   Vector2 endPoint = polygon[polygonLength-1];           
   endX = endPoint.x; 
   endY = endPoint.y;
   while (i<polygonLength) {
      startX = endX;           startY = endY;
      endPoint = polygon[i++];
      endX = endPoint.x;       endY = endPoint.y;
      //
      inside ^= ( endY > pointY ^ startY > pointY ) /* ? pointY inside [startY;endY] segment ? */
                && /* if so, test if it is under the segment */
                ( (pointX - endX) < (pointY - endY) * (startX - endX) / (startY - endY) ) ;
   }
   return inside;
}

Must be implemented by in the MathUtils class I think?