Randomly Selecting Points within a Given Polygon

References Used:

Stack Overflow – Random Points in a Quadrilateral

Wolfram Alpha Information on Points in a Triangle

I needed to be able to randomly but evenly distribute a number of objects within a 2D area so these are the sources I started with. The Stack Overflow question ended up being a very good starting point, but there were errors with the calculations that I needed to solve in order to actually use their logic.

Fixes from Stack Overflow

First calculation to fix was the originally randomly selected position of the object. It turned out that it was very close, but it actually only worked if v0 was the origin. It was simple enough to fix by adding v0 to the x equation.

The second equation to fix was the v3 equation. They were subtracting v0 twice which is incorrect (again something unnoticeable if v0 is that origin as you’re simply subtracting (0,0) twice). v0 should only be subtracted once to obtain the correct v3 value.

Finally, a correction that was found in the comments was that there are two rotation equations for x’ and the larger one is incorrect. In the text, it can be found that a rotation of pi is necessary. This can be mathematically applied by simply reversing (x – v3) to (v3 – x).

Work to do

Fixing these mathematical errors has appeared to give me the desired results with some further testing required after a final issue. I still need to determine how to let it know mathematically when to “flip” the x position into the x’ position. The original thought was to simply compare the distance from x to v3 and v0, and if it was closer to v3 (distance was less), then apply the x’ flip transformation. This however does not seem to be a geometrically sound solution as I am sometimes getting the flipped applied when it is within the proper bounds.