我不理解Physics.OverlapBox方法的用法。
我想在我的场景中在一个4x4的平面上放置十面墙。墙的宽度和位置是随机计算的。在创建循环中的奇数个循环中,墙旋转90度。
场景中显示的墙不应与其他墙发生碰撞...但它不起作用。

void Reset()
{
int walls = 10;
for (int w = 0; w < walls; w++)
{
for (int i = 0; i < 5; i++)
{
float x = Random.Range(-20f, 20f);
float z = Random.Range(-20f, 20f);
Vector3 center = new Vector3(x, 1.51f, z);
int scalex = Random.Range(4, 13);
Quaternion quaternion = Quaternion.identity;
if (w % 2 == 1)
quaternion=Quaternion.Euler(0, 0, 0);
else
quaternion=Quaternion.Euler(0, 90, 0);
Collider[] colliders = Physics.OverlapBox(center, new Vector3(scalex, 3, 1) / 2, quaternion);
Debug.Log(colliders.Length);
if (colliders.Length == 0)
{
GameObject wall = GameObject.CreatePrimitive(PrimitiveType.Cube);
wall.transform.position = center;
wall.transform.localScale = new Vector3(scalex, 3, 1);
wall.transform.rotation = quaternion;
wall.tag = "wall";
break;
}
}
}
}发布于 2021-09-04 17:35:42
在你的评论之后,我想我现在知道问题是什么了:
物理引擎根本不“知道”你的墙碰撞,因为物理引擎会在下一个FixedUpdate中更新。
您可能希望在每面墙之后调用Physics.Simulate,以便手动触发物理更新。
文档有点不清楚是否有必要,但你可能必须在循环之前禁用Physics.autoSimulation,并在完成墙创建后重新打开它。
发布于 2021-09-04 18:42:47
derHugo提出的解决方案(非常感谢)是从Start方法开始的。我给墙壁添加了旋转。没有碰撞。
代码:
public void Start()
{
Physics.autoSimulation = false;
for (int i = 0; i < 200; i++)
{
createWall();
Physics.Simulate(Time.fixedDeltaTime);
}
Physics.autoSimulation = true;
}
void createWall()
{
float x = Random.Range(-20f, 20f);
float z = Random.Range(-20f, 20f);
Vector3 position = new Vector3(x, 1.51f, z);
Quaternion rotation = Quaternion.Euler(0, Random.Range(0,360), 0);
int scalex = Random.Range(2, 5);
Collider[] colliders = Physics.OverlapBox(position, new Vector3(scalex, 1, 1)/2, rotation);
if (colliders.Length==0)
{
GameObject wall = GameObject.CreatePrimitive(PrimitiveType.Cube);
wall.transform.localPosition = position;
wall.transform.localScale = new Vector3(scalex, 3, 1);
wall.transform.rotation = rotation;
wall.tag = "wall";
}
}

https://stackoverflow.com/questions/69055600
复制相似问题