I have a 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it.
If it really simplifies the problem, I can limit
A. If you can restrict your input to parallelogram, this is really simple:
u
and v
.If your parallelogram is defined by the points ABCD such that AB, BC, CD and DA are the sides, then take your point as being:
p = A + (u * AB) + (v * AD)
Where AB
is the vector from A to B and AD
the vector from A to D.
B. Now, if you cannot, you can still use the barycentric coordinates. The barycentric coordinates correspond, for a quad, to 4 coordinates (a,b,c,d)
such that a+b+c+d=1
. Then, any point P
within the quad can be described by a 4-uple such that:
P = a A + b B + c C + d D
In your case, you can draw 4 random numbers and normalize them so that they add up to 1. That will give you a point. Note that the distribution of points will NOT be uniform in that case.
C. You can also, as proposed elsewhere, decompose the quad into two triangles and use the half-parallelogram method (i.e., as the parallelogram but you add the condition u+v=1
) or the barycentric coordinates for triangles. However, if you want uniform distribution, the probability of having a point in one of the triangle must be equal to the area of the triangle divided by the area of the quad.