unity生成模型边界框包括8个顶点

  • Post author:
  • Post category:其他


    void Start()
    {
        Bounds bounds = GetBounds(gameObject, transform.childCount > 0);
        Vector3 max = bounds.max;
        Vector3 min = bounds.min;
        Vector3 top1 = max;
        Vector3 top2 = new Vector3(max.x, max.y, min.z);
        Vector3 top3 = new Vector3(min.x, max.y, max.z);
        Vector3 top4 = new Vector3(min.x, max.y, min.z);
        Vector3 down1 = min;
        Vector3 down2 = new Vector3(max.x, min.y, min.z);
        Vector3 down3 = new Vector3(min.x, min.y, max.z);
        Vector3 down4 = new Vector3(min.x, min.y, min.z);
        Instantiate(Resources.Load<Transform>("Cube"), top1, Quaternion.identity);
        Instantiate(Resources.Load<Transform>("Cube"), top2, Quaternion.identity);
        Instantiate(Resources.Load<Transform>("Cube"), top3, Quaternion.identity);
        Instantiate(Resources.Load<Transform>("Cube"), top4, Quaternion.identity);
        Instantiate(Resources.Load<Transform>("Cube"), down1, Quaternion.identity);
        Instantiate(Resources.Load<Transform>("Cube"), down2, Quaternion.identity);
        Instantiate(Resources.Load<Transform>("Cube"), down3, Quaternion.identity);
        Instantiate(Resources.Load<Transform>("Cube"), down4, Quaternion.identity);

        Transform clone= Instantiate(Resources.Load<Transform>("Cube"),  bounds.center, Quaternion.identity);
        clone.localScale = bounds.size;
    }


    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;
    }



版权声明:本文为u010197227原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。