unity给子物体动态添加boxcollider(碰撞盒)

unity给子物体动态添加boxcollider(碰撞盒)

在工作中遇到过给物体拍照截图的功能,由于物体是动态加载并且大小不一,但是要求拍的照片正好被物体填充,因此需要动态计算物体大小,从而进行调整,这种方法也可以进行相机检测物体是否在视野内。使用方法非常简单,只需要将要计算的物体放到空物体的子物体下即可
如图所示

using UnityEngine;
public class TestBounds : MonoBehaviour
{
    
    
    private void Start()
    {
    
    
        var bounds = CalculateBounds(gameObject);
        var boxCollider = gameObject.GetComponent<BoxCollider>();
        if (boxCollider == null)
        {
    
    
            boxCollider = gameObject.AddComponent<BoxCollider>();
        }
        if (boxCollider)
        {
    
    
            boxCollider.center = bounds.center - transform.position;
            boxCollider.size = bounds.size;
        }
    }

    private Bounds CalculateBounds(GameObject pObj)
    {
    
    
        Renderer[] renderers = pObj.GetComponentsInChildren<Renderer>();
        if (renderers.Length > 0)
        {
    
    
            Bounds bounds = renderers[0].bounds;
            for (int i = 1; i < renderers.Length; i++)
            {
    
    
                bounds.Encapsulate(renderers[i].bounds);
            }
            return bounds;
        }
        else
        {
    
    
            return new Bounds();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44429570/article/details/128837714