unity 获取包围盒

1.获取中心点

        public Vector3 GetCenter(GameObject target)
        {
            Renderer[] mrs = target.gameObject.GetComponentsInChildren<Renderer>();
            Vector3 center = target.transform.position;
            if (mrs.Length != 0)
            {
                Bounds bounds = new Bounds(center, Vector3.zero);
                foreach (Renderer mr in mrs)
                {
                    bounds.Encapsulate(mr.bounds);
                }
                center = bounds.center;
            }
            return center;

        }

2.获取包围盒(通过Renderer)

        public Bounds GetBounds(GameObject target, bool include_children = true)
        {

            Renderer[] mrs = target.gameObject.GetComponentsInChildren<Renderer>();
            Vector3 center = target.transform.position;
            Bounds bounds = new Bounds(center, Vector3.zero);
            if (include_children)
            {
                if (mrs.Length != 0)
                {
                    foreach (Renderer mr in mrs)
                    {
                        bounds.Encapsulate(mr.bounds);
                    }
                }
            }
            else
            {
                Renderer rend = target.GetComponentInChildren<Renderer>();
                if (rend)
                {
                    bounds = rend.bounds;
                }
            }

            return bounds;

        }

3.获取包围盒(通过MeshFilter)

        public Bounds GetLocalBounds(GameObject target, bool include_children = true)
        {

            MeshFilter[] mfs = target.gameObject.GetComponentsInChildren<MeshFilter>();
            Vector3 center = target.transform.localPosition;
            Bounds bounds = new Bounds(center, Vector3.zero);
            if (include_children)
            {
                if (mfs.Length != 0)
                {
                    foreach (MeshFilter mf in mfs)
                    {
                        if (mf.mesh)
                        {
                            bounds.Encapsulate(mf.mesh.bounds);
                        }
                    }
                }
            }
            else
            {
                MeshFilter mf = target.GetComponentInChildren<MeshFilter>();
                if (mf && mf.mesh)
                {
                    bounds = mf.mesh.bounds;
                }
            }

            return bounds;

        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值