首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Physics.OverlapBox的错误使用

Physics.OverlapBox的错误使用
EN

Stack Overflow用户
提问于 2021-09-04 13:08:53
回答 2查看 84关注 0票数 1

我不理解Physics.OverlapBox方法的用法。

我想在我的场景中在一个4x4的平面上放置十面墙。墙的宽度和位置是随机计算的。在创建循环中的奇数个循环中,墙旋转90度。

场景中显示的墙不应与其他墙发生碰撞...但它不起作用。

代码语言:javascript
复制
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;
            }
        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-09-04 17:35:42

在你的评论之后,我想我现在知道问题是什么了:

物理引擎根本不“知道”你的墙碰撞,因为物理引擎会在下一个FixedUpdate中更新。

您可能希望在每面墙之后调用Physics.Simulate,以便手动触发物理更新。

文档有点不清楚是否有必要,但你可能必须在循环之前禁用Physics.autoSimulation,并在完成墙创建后重新打开它。

票数 0
EN

Stack Overflow用户

发布于 2021-09-04 18:42:47

derHugo提出的解决方案(非常感谢)是从Start方法开始的。我给墙壁添加了旋转。没有碰撞。

代码:

代码语言:javascript
复制
    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";
        }       
    }

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69055600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档