获取包围盒
public Bounds GetLocalBounds(GameObject modelStepObject)//获取包围盒
{
Renderer[] mfs = modelStepObject.GetComponentsInChildren<Renderer>();
Bounds bounds = new Bounds();
if (mfs.Length != 0)
{
bounds = mfs[0].bounds;
foreach (Renderer mf in mfs)
{
bounds.Encapsulate(mf.bounds);//和现有的包围盒比较,并扩展包围盒
}
}
return bounds;
}
根据包围盒创建碰撞盒
//获取包围盒
Bounds bounds = GetLocalBounds(highlightableObjects[i].gameObject);
//添加新的碰撞盒
BoxCollider bc = subStepObject.AddComponent<BoxCollider>();
bc.size = bounds.size;
bc.center = bc.center;
以上代码传入一个gameobject,返回一个这个gameobject下所有物体的共同的最小包围盒
注意:
- 物体必须有网格才能计算包围盒
- 不要对根物体进行旋转,否则包围盒的位置是错的