David
David

Reputation: 1

Instantiate prefab at random X and Y while not spawning on top of each other

So I'm working on a game for school, an endless vertical platformer. The issue I'm having is that I can spawn platforms no problem but I can't seem to figure out how to get them to either move or destroy when spawned on top of each other.

public void SpawnPlatforms(float floatValue)
{
    yPos = spawnPlatformsTo;     
        while (yPos <= floatValue)
        {

            xPos = Random.Range(-4.5f, 4.5f);
            Vector2 posXY = new Vector2(xPos, yPos);


            var platformInstatiated = Instantiate(platforms[Random.Range(0, 2)], posXY, Quaternion.identity);

                platformInstatiated.transform.parent = GameObject.Find("Platforms").transform;
                platformInstatiated.localScale = new Vector3(Random.Range(.3f, 1f), 1, 1);

            yPos += Random.Range(1f, 1.75f);
        }

    spawnPlatformsTo = floatValue;
}

any help at all would be GREATLY appreciated.

Upvotes: 0

Views: 731

Answers (1)

Joe
Joe

Reputation: 1067

Unity has a function for that called Bounds.Intersects.

Add all your platforms to a list or loop through all platforms in your scene and then check each one with

    //Fetch the Bounds from the Looped GameObject
    Bounds m_Bounds = loopedGameObject.GetComponent<Collider>().m_Collider.bounds;

    if(m_Bounds.Intersects(platformInstatiated.GetComponent<Collider>().bounds)
        Destroy(platformInstatiated);
        //Although you should really try to give it a new position instead of destroying it.

Upvotes: 1

Related Questions