Random points inside a parallelogram

前端 未结 11 629
失恋的感觉
失恋的感觉 2020-12-02 07:43

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

11条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 08:34

    A. If you can restrict your input to parallelogram, this is really simple:

    1. Take two random numbers between 0 and 1. We'll call then u and v.
    2. 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.

提交回复
热议问题