# Instantiate random position except on the player?

 0 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 more ▼ asked Jan 04 '12 at 02:30 AM stuthemoo 61 ● 9 ● 10 ● 11 add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

 0 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); ``` more ▼ answered Jan 04 '12 at 02:56 AM aldonaletto 41.4k ● 16 ● 42 ● 197 Thanks! That works great! Jan 04 '12 at 04:06 AM stuthemoo add new comment (comments are locked) 10|3000 characters needed characters left ▼ Viewable by all users

By Email:

Topics:

x1670
x884
x571

asked: Jan 04 '12 at 02:30 AM

Seen: 647 times

Last Updated: Jan 04 '12 at 04:06 AM