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

时间:2015-03-06 02:59:17

标签: c# unity3d game-engine

Iam试图制作一个简单的2d平台游戏。我设法移动了播放器和所有其他东西。我现在面临的问题是随机产生的游戏预制件是重叠的。所以我的问题是如何防止游戏对象的重叠。我使用的预制件具有不同的尺寸(长度)。 这是我使用的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));
    }
}

here is the screenshot of the game

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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