- Home /
Randomly Initiate Cubes - Prevent Same Position
Hello,
I'm spawning a load of cubes in my scene, using RandomRange to give it a random location. However I don't want to spawn a cube in the same position as any previous cubes.
So what it currently does is spawn a cube a 0,0,0 and then it caches that position.
It is then passed to a function that checks through all the cached positions and looks for any repeats, if so - then it will change the position, and keep doing so until it finds a new position.
But right now, my cubes just keep jumping everywhere, not finding a location. Need a fresh pair of eyes to look at this for me :/
Thanks:
function InitiateGame(){
print("Initiating Game!");
for(var i = 0; i < tileCount; i++){
//spawn tile at a position of 0,0,0
var tile = Instantiate(memoryTile, Vector3(0, 0, 0), transform.rotation);
tile.transform.parent = spawnLocation.transform;
//cache the location
tileCache[i] = tile.transform.position;
//check if random positions havnt overlapped
RandomLocation(tile.transform);
counter++;
yield WaitForSeconds(1);
}
}
function RandomLocation(tile : Transform){
for(var i = 0; i <= counter; i++){
while(tile.position == tileCache[i]){
print("Tile is same position");
//i think the jumping problem lies within here, as its caching the new location, so its still the same position!
tile.position = RandomVector();
tileCache[i] = tile.position;
yield;
}
}
}
function RandomVector(){
var posX = Mathf.Round(Random.Range(-0.4, 0.4) * 10) / 10;
var posY = Mathf.Round(Random.Range(-0.7, 0.7) * 10) / 10;
return Vector3(posX, posY, 0);
}
I'm sure theres a better way to do this too ? Any ideas?
In your RandomLocation function, you check if the positions are exactly the same. You should check if cubes intersect each other with colliders for example.
hope it helps.
Your answer
Follow this Question
Related Questions
C# Random spawn from an array 0 Answers
Spawn One Game Object In A Random Location After Object Has Been Used 1 Answer
Spawn Objects at Different Locations with Tags? 2 Answers
Spawn Object On Empty Object Location Different Each Time Game Starts 2 Answers
How to make levels spawn randomly? 0 Answers