我有几个房间是随机放置的,所以我必须检查一个房间是否重叠。房间大小为10x10,出于测试原因并排放置(它们在场景中不重叠)。地板是一个变换,由一个或多个变换组成(在这种情况下,一个正方形,但对于其他形式,它可能是2个或更多)。
要检查它们是否重叠,我有这个功能不起作用。调试日志总是在3到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;
}
顺便说一句,任何人阅读(2/2016)OverlapBox
都是一个全新的号召,Unity刚刚加入了最新版本。
编辑:正如Joe所建议的那样,OverlapBox'可见',但它们似乎位于正确的位置并且尺寸正确(红色是我的房间,灰色是碰撞器)。 ...
答案 0 :(得分:0)
我现在就开始工作了。每个OverlapBox都被正确放置,但它们仍然在相撞的地方,因为它们太靠近了#39;对象。这个改变修正了它:
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)