unity让BoxCollider自适配大小
1.一个空物体下面有若干个子物体,想要为空物体添加碰撞盒且碰撞盒还得要包裹所有子物体,手动拖动的话有点费时,费力,费眼,这时候有个工具是最好用的(如下图所示)
2.选中空物体点击(如下图所示)
3.就会变成如下图所示方便快捷
代码如下(编辑器脚本)
using UnityEngine; using UnityEditor; /// <summary> /// 选择一个物体给当前物体添加自适应碰撞盒 编辑器脚本 /// </summary> public class BoundsTool { [MenuItem("Tools/添加自适应碰撞盒")] private static void AutoBoxCollider() { //如果未选中任何物体 返回 GameObject gameObject = Selection.activeGameObject; if (gameObject == null) return; //计算中心点 Vector3 center = Vector3.zero; var renders = gameObject.GetComponentsInChildren<Renderer>(); for (int i = 0; i < renders.Length; i++) { center += renders[i].bounds.center; } center /= renders.Length; //创建边界盒 Bounds bounds = new Bounds(center, Vector3.zero); foreach (var render in renders) { bounds.Encapsulate(render.bounds); } //先判断当前是否有碰撞器 进行销毁 var currentCollider = gameObject.GetComponent<Collider>(); if (currentCollider != null) Object.DestroyImmediate(currentCollider); //添加BoxCollider 设置中心点及大小 var boxCollider = gameObject.AddComponent<BoxCollider>(); boxCollider.center = bounds.center - gameObject.transform.position; boxCollider.size = bounds.size; } }
(代码添加使用方法)
/// <summary> /// 自动调节碰撞盒的大小 /// </summary> /// <param name="obj_"></param> public void AutoBoxCollider(GameObject obj_) { //如果未选中任何物体 返回 GameObject gameObject = obj_; if (gameObject == null) return; //计算中心点 Vector3 center = Vector3.zero; var renders = gameObject.GetComponentsInChildren<Renderer>(); for (int i = 0; i < renders.Length; i++) { center += renders[i].bounds.center; } center /= renders.Length; //创建边界盒 Bounds bounds = new Bounds(center, Vector3.zero); foreach (var render in renders) { bounds.Encapsulate(render.bounds); } //先判断当前是否有碰撞器 进行销毁 var currentCollider = gameObject.GetComponent<Collider>(); if (currentCollider != null) UnityEngine.Object.DestroyImmediate(currentCollider); //添加BoxCollider 设置中心点及大小 var boxCollider = gameObject.AddComponent<BoxCollider>(); if (!gameObject.GetComponent<Highlighter>()) { gameObject.AddComponent<Highlighter>(); } boxCollider.center = bounds.center - gameObject.transform.position; boxCollider.size = bounds.size; }
最后在加一个设置模型中心点的方法吧,简单记录一下
List<GameObject> ObjZ = new List<GameObject>(); Vector3 posZ = Vector3.zero; /// <summary> /// 设置模型的中心点,方便做模型的移动 /// </summary> /// <param name="_trans"></param> public void SetModelPos(Transform _trans) { yield return new WaitForSeconds(0.2f); posZ = Vector3.zero; ObjZ.Clear(); for (int i = 0; i < _trans.childCount; i++) { posZ += (_trans.GetChild(i).GetComponent<MeshCollider>().bounds.center); ObjZ.Add(_trans.GetChild(i).gameObject); } posZ /= _trans.childCount; for (int i = 0; i < ObjZ.Count; i++) { ObjZ[i].transform.parent = null; } _trans.position = posZ; for (int i = 0; i < ObjZ.Count; i++) { ObjZ[i].transform.parent = _trans; } }
本次就这么多了哦,有需要会继续添加