Help with Random.insideUnitCircle

Hello,
I want to generate a position that is on the perimeter of a circle around the player with a radius of 5. Could someone explain why this is not working? I’m bad at vector topics and trying to learn. The vector3 the below code is outputting is still INSIDE the circle and not just the perimeter of it.

float radius = 5;
Vector2 rng = Random.insideUnitCircle; //Get a random position around a unit circle.
dir = new Vector3(rng.x,1, rng.y);
dir.Normalize(); //Ensure magnitude is 1 so we just have a direction
dir *= radius; //Multiply by the radius to determine how far.
dir += player.transform.position; //This makes the new position relative to the player.

Random.insideUnitCircle will generate a random point inside a circle, but not necessarily on the circle’s perimeter. We don’t have Random.onUnitCircle as we do with Random.onUnitSphere, but it’s easy to write;

var radius = 5f;
var angle = Random.value * (2f * Mathf.PI);
var direction = new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle));
var position = direction * radius;
3 Likes

Another way to turn the random point inside the unit circle into a point on the unit circle you can also simply normalize the point like this:

Vector2 rng = Random.insideUnitCircle.normalized;

I’m not sure why you set your y component to 1 which makes the vector skewed upwards. Your resulting vector would be a non linear distributed random point on the unit sphere cap at a 45° angle. So any point at the top part of the upper hemisphere could be the result. If you first normalize the Vector2 as I did and then set y to 1 and renormalize the result, you would get a unit vector that is pointing 45° upwards in a random direction.

So your question is kinda vague what your goal is. If you want a random point on the unit circle in the x-z plane, just do

Vector2 rng = Random.insideUnitCircle.normalized;
Vector3 dir = new Vector3(rng.x, 0, rng.y);

However the answer of @grizzly is a lot simpler and more direct (and doesn’t have a potential singularity in the really rare case of the point (0,0)).

4 Likes

I thought Unity staff is here to help the “little people” ;).

People are wondering why there is no such function built in. So maybe you could suggest it.