Rost
Rost

Reputation: 275

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)

Upvotes: 0

Views: 138

Answers (2)

user1196549
user1196549

Reputation:

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.

Upvotes: 3

Graeme
Graeme

Reputation: 1698

Determine if the shaded area is purely a triangle, if so, calculate the area of that triangle (a * b) / 2 , this would solve the right hand diagram.

For the left hand diagram, treat the area as a triangle and a rectangle. Compute the shaded area by adding together the triangles area and the rectangles area.

HTH

Upvotes: 0

Related Questions