Question by
scarcloud · Jul 24, 2016 at 02:22 PM ·
collision detection2d-physicsspawningcollision2d
Checking collision before instantiating prefab
Hello everyone,
in my code, I want to instantiate multiple prefabs while not having them collide with the main object the moment they are instantiated.
I checked the Scripting API and went through almost all of the possibilities to check for incoming collisions, and it seems that I am probably just missing something.
I'm providing the code which is relevant.
void SafeInstantiate(GameObject toInstance)
{
Vector3 rndmPos;
Vector2 toCheck;
// Pick a random position on the world map.
rndmPos = new Vector3 ( Random.Range (-boundaryX - 1f, boundaryX + 1f),
Random.Range (-boundaryY - 1f, boundaryY + 1f),
0);
// Prepare a Vector2 to check the collision with.
toCheck = new Vector2 (rndmPos.x, rndmPos.y);
Collider2D col = Physics2D.OverlapCircle (toCheck, 5.0f);
int loopBreak = 0; // for anti-freezing purposes
if (!col)
Debug.Log ("col is null");
while (col.name == "main" && loopBreak < 20) {
// The toInstance coordinates seem to collide with the main object. Reroll the coordinates.
Debug.Log ("Looping through");
rndmPos = new Vector3 ( Random.Range (-boundaryX - 1f, boundaryX + 1f),
Random.Range (-boundaryY - 1f, boundaryY + 1f),
0);
toCheck = new Vector2 (rndmPos.x, rndmPos.y);
col = Physics2D.OverlapCircle (toCheck, 5.0f);
loopBreak++;
}
// No collision, safe to instantiate.
Instantiate(toInstance, rndmPos, Quaternion.identity);
}
Do you see anything that would prevent my code from working properly? Need any more details?
Comment