简体   繁体   中英

How do you get a random point in a 3D plane

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?

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM