The problem lies in the selection of your angles. You have to respect two constraints.
First constraint The sum of the angles of a convex polygon is 180*(n-2)
degrees, where n
is the number of sides of your convex polygon [src].
Second constraint Given two lines, you have two choices for your angle :
You have to select the green angle. Your selection criteria is not very clear in your description, so I can't be sure if there is a mistake. To select the good angle, I think the simpliest thing to do is considering direction vector for each line. Compute u
the direction vector of your last line (pointing towards the new line). Compute v
, a direction vector of the new line. If (u^v) > 0
, v
is not correctly oriented, so you want to take -v
. Else if (u^v) < 0
, v
is correctly oriented. Details : u^v = u.x*v.y -u.y*v.x
So this lead us to our second constraint. Considering u
the direction vector of a side and u_next
the direction vector of the next side, we have u^u_next < 0
.
I think the second constraint is sufficient. We won't need the first one (but it is still good to know for general knowledge).
What to do Here's what I would do for your problem :
- Select a random line. Compute the direction vector
u0
such asu0.x > 0
. Initialize the listlistDV
of direction vector with u. Note: ifu.x = 0
, then selectu
such asu.y > 0
. - While(
listDV.last^listDV.first < 0
) {Select a random line, compute the direction vectoru
such aslistDV.last^u < 0
, push u at the end oflistDV
}. - Discard the last vector of
listDV
.
So now you have a list of direction vectors, which are parallel to your lines. The list forms a convex polygon.
Next will be the creation of your polygon. If you need help on this, let me know !