Random inside Unit Circle

Unity Engine has a feature to get a random Vector3 inside a unit Circle and I need help figuring out the how to do that.

The function Random.insideUnitCircle returns a random Vector3 which is inside the Unit Circle, or sphere?..

1 Like

Relevant StackOverflow question I found: geometry - Picking random points in the volume of sphere with uniform probability - Mathematics Stack Exchange

Should answer the question on how to do it for a sphere. Should be simple enough to do it for a circle.

If i were you, first i would set a start Vector3, and turn it into CFrame. Then multiply the CFrame with CFrame.Angles(math.rad(math.random(-360,360)),math.rad(math.random(-360,360)),math.rad(math.random(-360,360))) . Then i would multiply it again with CFrame.new(0,0,-math.random(MinRange,MaxRange))

Not the best method but you can create a better one. On phone so i hardly write code

I remember some old threads on here that had to do with this for bullet spread:
https://devforum.roblox.com/t/applying-a-spread-to-a-unit-vector/5945/5

2 Likes

To get a random vector inside a unit circle, I think you just get random angle then find the sin of that angle and the cosine of that angle

Picking a random direction and radius will not make a uniform distribution. It will tend to cluster at the center.

If you’re going for a uniform distribution, you’d want something like this:
image

(image taken from this post in StackExchange, which should also solve how to generate uniformly distributed points in a circle)

4 Likes

The simplest solution is to simply pick a random point inside a square until it falls inside the circle inscribed in that square. Since you may assume that the new Random feature would spread the points out uniformly over a square, then any subset (i.e. circle) you take from that square will also have uniform distribution of points.

This makes your code non-deterministic (i.e. it could fail to pick a point inside the circle) but the chance is typically pretty low, because for every pick you have a ~80% chance that it’s inside the circle. So the chance of having to pick twice is 20%, the chance of having to pick thrice is 4%, the chance of picking four times is .8%, etc.

5 Likes

Well, I’ve discovered a method for generating a random point but it only outputs the X and the Y position.


credit to this article

1 Like

Thanks for this too, but I’ll be using the one from einsteinK because I was planning it for bullet spread.

I would just do this if you don’t understand the mathematics yourself. That way, while not ideal code, it will be code that you can understand and modify in the future.

Yeah, my code there doesn’t apply to this. Like @XAXA points out it will concentrate the points around the centre (which I might add, is actually the behavior that you want in a lot of cases such as bullet spread), while function that the OP referenced gives a uniform distribution.

1 Like