Check if items are overlapping

女生的网名这么多〃 提交于 2021-02-17 05:52:21

问题


I have a few rooms which are placed randomly so I have to check if a room is overlapping. The rooms have a size of 10x10 and are for test reasons placed exactly side by side (they don't overlap in the scene). The Floor is a Transform which consists out of 1 or more Transforms (in this case out of one square but for other forms it it could be 2 or more).

To check if they are overlapping I have this function which doesn't work. Debug log is always something between 3 and 61..

public bool Overlapping()
{
    //Lists for the position and of the size of each floor transform
    List<Vector3> positions = new List<Vector3>();
    List<Vector3> sizes = new List<Vector3>();
    //Check if floor consists out of more than 1 transform
    if (Floor.childCount > 0)
        foreach (Transform t in Floor)
        {
            positions.Add(t.position);
            sizes.Add(t.lossyScale);
        }
    else
    {
        positions.Add(Floor.position);
        sizes.Add(Floor.lossyScale);
    }

    //Save old room pos and move it out of the way
    Vector3 position = this.transform.position;
    this.transform.position = new Vector3(0, 100, 0);

    //Check if any floor transform would overlap
    for (int i = 0; i < positions.Count; i++)
    {
        //Make overlap box visible
        GameObject rec = GameObject.CreatePrimitive(PrimitiveType.Cube);
        rec.transform.localScale = sizes[i];
        rec.transform.localPosition = positions[i];
        rec.transform.localRotation = Quaternion.Euler(0, 0, 0);

        //Returns the colliders which are overlapping
        if (Physics.OverlapBox(positions[i], sizes[i] / 2).Length > 0)
        {
            Debug.Log(Physics.OverlapBox(positions[i], sizes[i] / 2).Length);
            //return this room to it's old position
            this.transform.position = position;
            return true;
        }
    }

    //return this room to it's old position
    this.transform.position = position;
    return false;
}

By the way for anyone reading (2/2016) OverlapBox is a brand-new call Unity just added to the latest verion.

Edit: As suggested by Joe I made the OverlapBox 'visible', but they seem to be in the correct positions and in the correct sizes (Red is my room, gray are the colliders)....


回答1:


I got it working now. Each OverlapBox was placed correctly, but they where still colliding, because they were 'too close' to the object. This change fixed it:

if (Physics.OverlapBox(positions[i], new Vector3(sizes[i].x - 0.01f, sizes[i].y - 0.01f, sizes[i].z - 0.01f) / 2, rotations[i]).Length > 0)


来源:https://stackoverflow.com/questions/35254059/check-if-items-are-overlapping

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