First define the circle radius and its center:
var radius:Number = 100;
var center:Point = new Point(35, 70);
Then generate a random angle in radians from the center:
var angle:Number = Math.random() * Math.PI * 2;
Then generate an effective radius of the returned point, so it'll be inside given radius
. A simple Math.random()*radius
won't do, because with this distribution the produces points will end up in the inner circle of half radius half of the time, but the square of that circle is a quarter of original. To create a proper distribution, the function should be like this:
var rad:Number=(Math.random()+Math.random())*radius; // yes, two separate calls to random
if (rad>radius) { rad=2*radius-rad; }
This function produces a value that has its probability function linearly increasing from 0 at zero to maximum at radius
. It happens because a sum of random values has a probability density function equal to convolution of all the random values' individual density functions. This is some extended maths for an average grade person, but a kind GIF is presented to draw a graph of convolution function of two uniformed distribution density functions explained as "box signals". The if
operator folds the resultant function over its maximum, leaving only a sawtooth-shaped graph.
This function is selected because the square of a circle strip located between radius=r
and radius=r+dr
increases linearly with increasing r
and very small constant dr
so that dr*dr<<r
. Therefore, the amount of points generated close at the center is smaller than the amount of points generated at the edge of the circle by the same margin as the radius of center area is smaller than the radius of the whole circle. So overall, points are evenly distributed across the entire circle.
Now, get your random position:
var result:Point = new Point(
center.x + Math.cos(angle) * rad,
center.y + Math.sin(angle) * rad
);
To get a random point ON the circle (on the edge of the circle of a given radius), use radius
instead of rad
.
PS: The example ended up being overloaded by explanation of maths.