- Home /
Position objects around other object forming a circle
I have an object at some position. I need to spawn other objects and place them at random positions around this object, forming a circle with center on the first object and at some x distance(radius) from it. How can i calculate the transform position that i need to place the objects ?
Thank You
Answer by aldonaletto · Sep 26, 2011 at 01:49 AM
You can use the function below - it returns a Vector3 position with the center and radius specified:
function RandomCircle(center:Vector3, radius:float): Vector3 { // create random angle between 0 to 360 degrees var ang = Random.value * 360; var pos: Vector3; pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad); pos.y = center.y + radius * Mathf.Cos(ang * Mathf.Deg2Rad); pos.z = center.z; return pos; }
// How to use:
var center = transform.position;
for (i = 0; i < numObjects; i++){
var pos = RandomCircle(center, 10);
// make the object face the center
var rot = Quaternion.FromToRotation(Vector3.forward, center-pos);
Instantiate(prefab, pos, rot);
}
Thanks for your help, to make the funktion RandomCircle work you need to add "return(pos);" at the end
You're right, @maglat - I just forgot the return pos; instruction!
I would also suggest you check out Random.insideUnitCircle(), which returns a random point in the unity circle which can be normalized then multiplied by your radius to get what you want. That being said the (blasted) thing returns a Vector2, so Aldo solution certainly better, if not more efficient.
Thanks! what should be changed to get the angle from a sphere ins$$anonymous$$d of a circle? pos.z = center.z + ?
Answer by tesan · Aug 09, 2017 at 07:26 PM
you can watch this plugin: http://u3d.as/Un7, I think it's what you want