- Home /
Question by
stuthemoo · Jan 04, 2012 at 02:30 AM ·
instantiatepositionrandom
Instantiate random position except on the player?
I'm making a top-down shooter and I want to spawn objects around the player in random positions unless the random position is within a certain distance of the player.
This will spawn the object in a random spot on the screen:
pos = Vector3(Random.Range(-10,10), 0, Random.Range(-10,10));
Instantiate(myObject,pos,transform.rotation);
But I want to regenerate the random position if it is too close to the player. How could I achieve this?
Many thanks, Stuart
Comment
Answer by aldonaletto · Jan 04, 2012 at 02:56 AM
You can repeat the pos generation whenever the position is below some distance:
do { pos = Vector3(Random.Range(-10.0,10.0), 0, Random.Range(-10.0,10.0)); } while (Vector3.Distance(pos, transform.position) < minDistance); Instantiate(myObject,pos,transform.rotation);NOTE: Using integers (-10, 10) in Random.Range will return an integer value between -10 and 9. If you pass float numbers to it like in the code above, the value returned will be a float between -10 and 10. But you have an even better alternative - use Random.insideUnitCircle instead:
do { var rnd: Vector2 = 10 * Random.insideUnitCircle; pos = Vector3(rnd.x, 0, rnd.y); } while (Vector3.Distance(pos, transform.position) < minDistance); Instantiate(myObject,pos,transform.rotation);
Your answer
![](https://koobas.hobune.stream/wayback/20220613062642im_/https://answers.unity.com/themes/thub/images/avi.jpg)