How to find a random point in a quadrangle?

后端 未结 9 1681
忘掉有多难
忘掉有多难 2021-02-08 12:53

I have to be able to set a random location for a waypoint for a flight sim. The maths challenge is straightforward:

\"To find a single random location within a quadrangl

相关标签:
9条回答
  • 2021-02-08 13:40

    I would divide your quadrangle into multiple figures, where each figure is a regular polygon with one side (or both sides) parallel to one of the axes. For eg, for the figure above, I would first find the maximum rectangle that fits inside the quadrangle, the rectangle has to be parallel to the X/Y axes. Then in the remaining area, I would fit triangles, such triangles will be adjacent to each side of the rectangle.

    then it is simple to write a function:

    1) get a figure at random. 2) find a random point in the figure.

    If the figure chosen in #1 is a rectangle, it should be pretty easy to find a random point in it. The tricky part is to write a routine which can find a random point inside the triangle

    0 讨论(0)
  • 2021-02-08 13:45

    So, it depends on how you want your distribution.

    If you want the points randomly sampled in your 2d view space, then Jacob's answer is great. If you want the points to be sort of like a perspective view (in your example image, more density in top right than bottom left), then you can use bilinear interpolation.

    Bilinear interpolation is pretty easy. Generate two random numbers s and t in the range [0..1]. Then if your input points are p0,p1,p2,p3 the bilinear interpolation is:

    bilerp(s,t) = t*(s*p3+(1-s)*p2) + (1-t)*(s*p1+(1-s)*p0)
    

    The main difference is whether you want your distribution to be uniform in your 2d space (Jacob's method) or uniform in parameter space.

    0 讨论(0)
  • 2021-02-08 13:46

    You may randomly create points in a bound-in-box only stopping after you find one that it's inside your polygon.

    So:

    1. Find the box that contains all the points of your polygon.
    2. Create a random point inside the bounds of the previously box found. Use random functions to generate x and y values.
    3. Check if that point is inside the polygon (See how here or here)
    4. If that point is inside the polygon stop, you're done, if not go to step 2
    0 讨论(0)
提交回复
热议问题