I’m using a Java Polygon object, which stores an array of points which define the lines that make up the shape.
How would I go about selecting a random point on one of these lines? Are there any methods in the Polygon class that would make this easier?
To clarify, I want to pick a random point from any position on the edge of the polygon, not necessarily from the set of defined vertices.
The first thing you have to do is find the perimeter of the polygon.
Now find a random number the range of 0 to perimiter.
Then, iterate over the segments of the polygon, subtracting the length of the segment from your value until the length of the next segment is longer than your current value.
Pretend you’re “walking that distance” along the segment equal to your remaining value, and you’ll have a random point on the perimeter.
================================
Another viable option would be to pick a random segment biased by their length (you could cache the thresholds for each polygon) and then pick a random point on the segment that was randomly picked. Would be faster for large polygons (order 1 after you cache the thresholds) but would go through twice the random numbers.