Prevent overlapping of spawned game objects in unity

不羁岁月 提交于 2019-12-25 04:23:02

问题


Iam trying to make a simple 2d platformer game in unity. I managed to move the player and all other stuffs. The problem now i am facing is that the prefabs that randomly spawned onto the game is overlapping. So my question is how to prevent the overlapping of game objects. The prefabs i used is having different dimension(length). Here is the c# code i used:

    public class spawnscript : MonoBehaviour {
    public GameObject[] obj;
    public float spawnMin;
    public float spawnMax;

    // Use this for initialization
    void Start () {
        Spawn ();
    }

    void Spawn()
    {
        Instantiate (obj [Random.Range (0, obj.GetLength (0))], transform.position, Quaternion.identity);
        Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
    }
}


回答1:


void Spawn() {
    Instantiate(obj [Random.Range (0, obj.GetLength (0))], transform.position +(ADD OFFSET HERE WITH PREVIOUS OBJECTS Position), Quaternion.identity);
    Invoke("Spawn", Random.Range (spawnMin, spawnMax));
}



回答2:


List<Vector3> existingPositions = new List<Vector3>();
void Spawn()
{
    var pos = RandomizePosition();
    if(HasOverlapped(existingPositions, pos)) // Your own logic to implement
    {
         //Either randomize the position again, or give it an offset, up to you
    }
    else
    {
        Instanciate(pos, ...);
        existingPositions.Add(...);
    }
}


来源:https://stackoverflow.com/questions/28891679/prevent-overlapping-of-spawned-game-objects-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!