fortpointuiguy - 4 months ago 20

ActionScript Question

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

}

Answer

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.*

Source (Stackoverflow)

Comments