转载 Unity3D研究院之自动计算所有包围盒的中心点(七)

美术在做场景的时候可能会出现这个情况? 如下图所示,这个地块的中心点远离模型十万八千里?与其相信美术或者策划我觉得程序要更相信自己!!

Unity3D研究院之自动计算所有包围盒的中心点(七) - 雨松MOMO程序研究院 - 1

 1 [MenuItem ("MyMenu/Do Test")]
 2     static void Test () 
 3     {
 4         Transform parent =     Selection.activeGameObject.transform;
 5         Vector3 postion = parent.position;
 6         Quaternion rotation = parent.rotation;
 7         Vector3 scale = parent.localScale;
 8         parent.position = Vector3.zero;
 9         parent.rotation = Quaternion.Euler(Vector3.zero);
10         parent.localScale = Vector3.one;
11  
12  
13         Vector3 center = Vector3.zero;
14         Renderer[] renders = parent.GetComponentsInChildren<Renderer>();
15         foreach (Renderer child in renders){
16             center += child.bounds.center;   
17         }
18         center /= parent.GetComponentsInChildren<Transform>().Length; 
19         Bounds bounds = new Bounds(center,Vector3.zero);
20         foreach (Renderer child in renders){
21             bounds.Encapsulate(child.bounds);   
22         }
23     
24         parent.position = postion;
25         parent.rotation = rotation;
26         parent.localScale = scale;
27  
28         foreach(Transform t in parent){
29             t.position = t.position -  bounds.center;
30         }
31         parent.transform.position = bounds.center + parent.position;
32  
33     }

OK 大功告成。 中心点居中了。。

Unity3D研究院之自动计算所有包围盒的中心点(七) - 雨松MOMO程序研究院 - 2

posted @ 2016-04-14 19:55  lpcoder  阅读(680)  评论(0)    收藏  举报