欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-16 15:26:04
...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SetModel : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Vector3 postion = transform.position;
        Quaternion rotation = transform.rotation;
        Vector3 scale = transform.localScale;
        transform.position = Vector3.zero;
        transform.rotation = Quaternion.Euler(Vector3.zero);
        transform.localScale = Vector3.one;
        Collider[] colliders = transform.GetComponentsInChildren<Collider>();

        foreach (Collider child in colliders)
        {
            DestroyImmediate(child);
        }

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

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

    void Update()
    {

    }
}

原文https://blog.csdn.net/Delesgues/article/details/87712113

上一篇: hdu 1286

下一篇: ES6之尾递归