x


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

more ▼

asked Jan 04 '12 at 02:30 AM

stuthemoo gravatar image

stuthemoo
61 9 10 11

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

1 answer: sort voted first

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 gravatar image

aldonaletto
41.4k 16 42 197

Thanks! That works great!

Jan 04 '12 at 04:06 AM stuthemoo
(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:

x1670
x884
x571

asked: Jan 04 '12 at 02:30 AM

Seen: 647 times

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