Random points inside a parallelogram

前端 未结 11 631
失恋的感觉
失恋的感觉 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:43

    By "general" do you mean all non-parallelogram 4-side polygons in general or all possible polygons?

    How about drawing a random line connecting the 4 sides e.g. If you have this:

    .BBBB.
    A    C
    A    C
    .DDDD.
    

    Then generate a random point on a unit square, then mark the point on the line B and D at the percentage of distance on the X axis. Do the same on line A and C using value from the Y axis.

    Then connect the point on line A to line C and line B to line D, the intersection point is then used as the random point.

    It's not uniform because rounding errors will aid certain points but it should be close if you are working with floating points values.

    Implementation should be rather easy, too, since you are already working with polygons. You should already have code that does those simple tasks.

    Here's a quick pseudocode:

    void GetRandomPoint(Polygon p, ref float x, ref float y) {
    
        float xrand = random();
        float yrand = random();
    
        float h0 = p.Vertices[0] + xrand * p.Vertices[1];
        float h1 = p.Vertices[2] + yrand * p.Vertices[3];
    
        float v0 = p.Vertices[0] + xrand * p.Vertices[2];
        float v1 = p.Vertices[1] + yrand * p.Vertices[3];
    
        GetLineIntersection(h0, h1, v0, v1, x, y);
    
    }
    

提交回复
热议问题