简体   繁体   English

防止统一产生的游戏对象重叠

[英]Prevent overlapping of spawned game objects in unity

Iam trying to make a simple 2d platformer game in unity. Iam试图统一制作一个简单的2D平台游戏。 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: 这是我使用的C#代码:

    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));
    }
}

这是游戏的屏幕截图

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));
}
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(...);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM