-1

I need to get a random point in a plane. Let's say we have a quad and know the positions of the four vertices that make it up. How do I get a random point that's within that quad?

  • Let the corners be at `a`, `b`, `c` and `d` and let `a` and `c` be opposite corners. Your random point is `a + (b-a)*r1 + (d-a)*r2` where `r1` and `r2` are random values between 0 and 1... – fabian Jan 20 '22 at 19:38

2 Answers2

1

Given a quad like:

pD ---- pC
|       |
|       |
|       |
pA ---- pB

You can get a random point by getting a random point within that normalized square and use the A-to-B and A-to-D vectors as a coordinate basis.

In practice:

// gets a value between 0.0 and 1.0
float randomVal();

vec3 point_in_quad(vec3 pA, vec3 pB, vec3 pC, vec3 pD) {
  return pA + (pB - pA) * randomVal() + (pD - pA) * randomVal();
}
  • This only works for parallelograms. Since `pC` is not used, there's point that are picked just outside `pC` or there's points around `pC` that are never picked – Jeffrey Jan 20 '22 at 19:40
0

If you assume convexity, you can do it with:

// gets a value between 0.0 and 1.0
float randomVal();

vec3 point_in_quad(vec3 pA, vec3 pB, vec3 pC, vec3 pD) 
{
    vec3 ab =  pA + (pB - pA) * randomVal();
    vec3 dc =  pD + (pC - pD) * randomVal();
    vec3 r =  ab + (dc - ab) * randomVal();
    
    return r;
}

Basically, pick two randoms points. One on AB and one on CD. Then pick a point randomly in between those two.

Credits to @frank for the framework.

For uniformly random point on the quad, see:

Random points inside a parallelogram

This question is badly named. The answer applies to any quad.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
  • This won't result in an even distribution (area-wise) for non-parallelograms though. –  Jan 20 '22 at 19:47
  • You are correct. It would need to be corrected with weighting based on width. It does affect your solution, too, though. Let me see If I can weight it correctly. – Jeffrey Jan 20 '22 at 19:50