1
votes

Not sure what I'm doing wrong here so I was looking to see if anyone had any thoughts or suggestions. I'm trying to create a function that returns a random point WITHIN a circle. The following code gives me random points along the edge of the circle. Any thoughts on what I'm doing wrong here? Thanks!

private function getPointInCircle(tmpRadius:int):Point {
    var x:int;
    var y:int;

    var a:Number = Math.random() * 360;
    x = radius * Math.cos(a * (Math.PI / 180));
    y = radius * Math.sin(a * (Math.PI / 180));

    trace("x: " + x + "y: " + y);
    return new Point(x, y);
}
3

3 Answers

4
votes

You need two degrees of freedom, one is the angle, which you had, and the other is the distance from the center:

var d:Number = Math.random()*radius
var a:Number = Math.random()*2*Math.PI;
x = d*Math.cos(a);
y = d*Math.sin(a);

If you have your circle centered in (x0,y0) and not in (0,0) you modify like this:

x = x0 + d*Math.cos(a);
y = y0 + d*Math.sin(a);

Trivia: The circle is just the border line. If you want to refer to the area delimited by the border, you say disk.

1
votes

Try a random angle and random radius in a circular coordinate system, then convert to cartesian. Also, did you notice that your parameter is tmpRadius and in your function you are using radius?

var a = Math.random() * 2 * Math.PI;
var r = Math.random() * radius;
var x = r * Math.cos(a);
var y = r * Math.sin(a);
0
votes

The other answers do provide a sort of random point inside a circle, but they are not uniformly distributed. Regions near the center will have a higher concentration of points per unit area than regions near the rim.

To get a uniform distribution, you can either:

(a) Find a random point in the axis square around the circle.

x = (Math.random() * 2 - 1) * radius;
y = (Math.random() * 2 - 1) * radius;

Test whether it's actually in the circle (x * x + y * y <= r * r). Repeat until you find a valid point.

(b) Do a little math transformation to get appropriately distributed distance and angle.

uniform_random = P(dist < r) = (pi r^2) / (pi radius^2) = r^2 / radius^2

r = radius * sqrt(uniform_random)

var r = radius * sqrt(Math.random());
var theta = 2 * Math.PI * Math.random();
var x = r * Math.cos(theta);
var y = r * Math.sin(theta);