给物体添加碰撞体,使碰撞器刚好包围物体

本文介绍了一种在Unity中通过代码自动为模型或模型组精确添加BoxCollider的方法,确保碰撞器完美贴合模型,适用于单个或多个模型的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Unity中,给模型添加碰撞器时,若想精准定位模型,即让碰撞器刚好包围住模型,普通操作方式在为模型添加碰撞器后,调整碰撞器尺寸及位置比较麻烦,如下分享一个通过代码来给模型或模型组添加碰撞器的方式。

这里我们使用添加菜单的方式,将功能附加到菜单栏里。方便选中要添加碰撞器的模型后,从菜单中点击选项按钮为其添加碰撞器。

[MenuItem("MyMenu/AddBoxCollider")]

原理上,首先销毁所有子物体的碰撞器,然后通过获取所有子物体的Renderer,计算出所有Renderer的中心点及最大边界,然后创建Collider,以BoxCollider举例,此时BoxCollider将以模型或模型组的最大长、宽、高重新创建碰撞器。

可以看到,此时的碰撞器刚好包围模型。

当有两个或以上模型时,需要将所有模型放到一个GameObject下,然后给这个父物体GameObject添加碰撞器。

以下是完整代码:

    [MenuItem("MyMenu/AddBoxCollider")]
    static void Test()
    {
        Transform parent = Selection.activeGameObject.transform;
        Vector3 postion = parent.position;
        Quaternion rotation = parent.rotation;
        Vector3 scale = parent.localScale;
        parent.position = Vector3.zero;
        parent.rotation = Quaternion.Euler(Vector3.zero);
        parent.localScale = Vector3.one;

        Collider[] colliders = parent.GetComponentsInChildren<Collider>();
        foreach (Collider child in colliders)
        {
            DestroyImmediate(child);
        }
        Vector3 center = Vector3.zero;
        Renderer[] renders = parent.GetComponentsInChildren<Renderer>();
        foreach (Renderer child in renders)
        {
            center += child.bounds.center;
        }
        center /= parent.GetComponentsInChildren<Transform>().Length;
        Bounds bounds = new Bounds(center, Vector3.zero);
        foreach (Renderer child in renders)
        {
            bounds.Encapsulate(child.bounds);
        }
        BoxCollider boxCollider = parent.gameObject.AddComponent<BoxCollider>();
        boxCollider.center = bounds.center - parent.position;
        boxCollider.size = bounds.size;

        parent.position = postion;
        parent.rotation = rotation;
        parent.localScale = scale;
    }

代码是网上找的,亲测可用,欢迎纠错

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值