- Home /
Checking all elements of an array?
I am trying to spawn a series of objects where object is at least a certain amount of distance away from any other object. To accomplish this, I store previously generated positions in an array and then check the current position against them. The problem with my code now is that only checks the position of the previously spawned object and not the entire array. How can I check every position in the array? Thanks.
var MyObject :GameObject;
var MyPositions: Vector2[];
var Temporary : Vector2;
var Current : int;
function Start(){
for (var i : int = 1;i < Current; i++) {
Temporary.x = Random.Range(-5f,5f);
Temporary.y = Random.Range(-5f,5f);
if(Vector2.Distance(Temporary,MyPositions[i-1]) <= 1.5f)
i -= 1;
if(i == (Current-1))
MyPositions[Current-1] = Temporary;
}
Instantiate(MyObject,MyPositions[Current-1],transform.rotation);
Current +=1;
if(Current<=10)
Invoke("Start",1);
}
Answer by Uldeim · Nov 07, 2014 at 10:39 PM
That's an interesting approach, but I'd recommend against using recursion for something like this.
A naive implementation of what you're looking for might look like this:
var TooClose : bool;
var MAX_SPAWN : int = 10;
function Start() {
for (var i : int = 0; i < MAX_SPAWN; i++)
{
Temporary.x = Random.Range(-5f,5f);
Temporary.y = Random.Range(-5f,5f);
TooClose = false;
for (var j : int = 0; j < i; j++)
{
if(Vector2.Distance(Temporary,MyPositions[j]) <= 1.5f)
{
TooClose = true;
break;
}
}
if (TooClose)
{
i--;
continue;
}
MyPositions[i] = Temporary;
Instantiate(MyObject,MyPositions[i],transform.rotation);
}
}
As a side note, having done this in the past, I recommend against generating distance separated objects like this. It can lead to huge load times if you get an unlucky couple of random values, and infinite load times if you accidentally mess up your distance to size-of-map ratio. I'd look into two dimensional random distribution algorithms instead, if I were you. Unfortunately, I don't know any off the top of my head to recommend.
Your answer
Follow this Question
Related Questions
Puzzle + Grid Instantiate - Random 2 Answers
How to compare and detect overlapping gameObject Prefabs using maths 0 Answers
How to loop through and remove Instantiate Gameobject clones 2 Answers
OverlapSphere for parallel arrays 1 Answer
IndexOutOfRangeException: Array index is out of range when using an Array and instantiating 2 Answers