Search code examples
algorithmgeometry2darearectangles

Find area of 2d polygon formed by rect and line


I'm making game in Unity. There's a rectangle intersected by a straight line. I need to find which part of rect is bigger and how much. Do anyone knows algorithm how to do this? Example

Rect and lines are set with points (4 for rect and 2 for lines)


Solution

  • The implicit equation of the line is

    S(x,y) = (x - x0) (y1 - y0) - (y - y0) (x1 - x0) = 0
    

    When you plug the coordinates of a corner, the sign of S(x, y) tells you on what side of the line you are. And better, if you evaluate Sa and Sb at two corners and they have different signs, the intersection is at a fraction Sa / (Sa - Sb) along the side ab.

    Now, process all four edges in turn in clockwise order. For every edge, keep the starting corner if positive and keep the intersection if any. In the end, you'll get 0 to 5 points defining the convex polygon which is in the positive domain.

    enter image description here

    The area is found by the shoelace formula.