Random generation of Asteroids


i want to generate an Astroid field.

I want to place them at random places around a coordinate with a max and min amount of asteroids or something like that. I found the instantiate command but im not sure how i would make the center var and the random range from that. And how do i make it so the “SpawnLoop” only runs as long as i want asteroids to be generated.I have 5 diffrent Asteroid Prefabs that i want to randomly choose from. And is there a way to only spawn in places that are far enough away from other asteroids?

I know these are alot of questions but it would be very helpful if someone can explain and help me with those.

Thanks in advance.

You can find something like that in a tutorial series on the website under learn /tutorials/ projects/project space shooter it’s very good too for understanding basics.

The only harder part of your question is “to only spawn in places that are far enough away from other asteroids”. One solution is to make all of your models closely fit inside a set size sphere (unit sphere is easiest). Then you can use Physics.CheckSphere() to check to see if a position is available. Here is a bit of code to demonstrate:

#pragma strict
var asteroids : GameObject[];  // Initialized in the inspector
private var origin = Vector3.zero;

var minSize = 0.2;
var maxSize = 1.5;

var minCount = 20;
var maxCount = 45;

var minDistance = 3.0;
var maxDistance = 15.0;
function Start () {
    origin = transform.position;
	GenerateAsteroids(Random.Range(minCount, maxCount));
function GenerateAsteroids (count : int) {
	for (var i = 0; i < count; i++) {
		var size = Random.Range(minSize, maxSize);
		var prefab = asteroids[Random.Range(0, asteroids.Length)];
		for (var j = 0; j < 100; j++) {
			var pos = Random.insideUnitSphere * (minDistance + (maxDistance - minDistance) * Random.value);
			pos += origin;
			if (!Physics.CheckSphere(pos, size / 2.0)) {
		var go = Instantiate(prefab, pos, Random.rotation);
		go.transform.localScale = Vector3(size, size, size);

In the inspector you need to initialize the ‘asteroids’ array with the prefabs for the asteroids.

The for() loop using ‘j’ repeatedly tries to place the object in a position that does not conflict using the CheckSphere() call. Note you can increase the ‘radius’ parameter to push things further apart as needed. Also note that it does not try forever. It tries 500 times. The reason is that certain parameters (too tight an area and/or too big of object), can result in no areas to place an object without overlapping. Without the limit on the number of tries, the app would hang. I don’t know how many asteroids you will have, but it would be more efficient to keep your own list and do your own distance check rather than relying on CheckSphere(). Test your app for performance and see if you need to make the change.

Anyone else getting there asteroids floating away? Is there a way to prevent them from just floating too far away?