x


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

more ▼

asked Sep 26, 2011 at 01:26 AM

fgmanfredini gravatar image

fgmanfredini
1 3 2 2

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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

more ▼

answered Sep 26, 2011 at 01:49 AM

aldonaletto gravatar image

aldonaletto
56.8k 31 77 291

Thanks for your help, to make the funktion RandomCircle work you need to add "return(pos);" at the end

Jul 30, 2012 at 10:46 AM maglat

You're right, @maglat - I just forgot the return pos; instruction!

Jul 31, 2012 at 12:33 AM aldonaletto

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.

Jul 31, 2012 at 02:12 AM Avaista
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1679
x1468
x102
x29

asked: Sep 26, 2011 at 01:26 AM

Seen: 4758 times

Last Updated: Jul 31, 2012 at 02:12 AM