- Home /
Avoid overlapping of random spawned prefab
I used a code to spawn 2 different prefabs .The script is working but sometimes the objects get's overlapped ,and I can't figure out how to avoid this overlapping.
void SpawnSpike()
{
//the bottom point of the screen
Vector2 min = Camera.main.ViewportToWorldPoint (new Vector2 (0, 0));
//this is the top-right point of the screen
Vector2 max = Camera.main.ViewportToWorldPoint (new Vector2 (1, 1));
//instantiate an enemy1
GameObject anSpikesGO = (GameObject)Instantiate (SpikesGO);
anSpikesGO.transform.position = new Vector2 (Random.Range (-min.x, -max.x), -max.y);
//Schedule when to spawn next enemy
ScheduleNextSpikeSpawn ();
}
void ScheduleNextSpikeSpawn()
{
float spawnInSeconds;
if (maxSpawnRateInSeconds > 2f)
{
//pick a number between 1 to max
spawnInSeconds = Random.Range (2f, maxSpawnRateInSeconds);
}
else
spawnInSeconds = 2f;
Invoke ("SpawnSpike", spawnInSeconds);
}
Cast Physics.OverlapBox or similar shape before instantiation, using the object's renderer.bounds as the shape dimensions and casting against the layer the other already existing objects are in.
Answer by Oshroth · Apr 01, 2016 at 12:41 AM
Use Physics2D to check if the spawn position is occupied and keep checking random positions until you find a blank space.
int attempts = 0;
do {
// Get a Random spawn Position
if(!Physics2D.OverlapArea(topLeft, BottomRight)) { // Check the bounds of the spawn position
break;
}
Debug.Log("Collision during spawn at: " + temp);
} while (++attempts <= 10); // Limit spawn attempts to prevent infinite loop
if(attempts > 10) {
Debug.Log("Failed to find a clear spawn point");
}
Answer by FlightOfOne · Mar 31, 2016 at 10:55 PM
There's several ways to accomplish this but I think the easiest would be to use a collider or trigger and using tags. If it collided with an object with the same take, re-position it again using random range, as you have done.
Answer by Lancemaker_ · Jul 19, 2016 at 01:52 PM
use raycast using the object witht/hight divided / 2 as the max distance on -x, +x,-y,+y directions. if it returns anything repeat until you find a proper spot.