就是找出 bounds max的一个点,计算与摄像机的距离,然后确定它
https://answers.unity.com/questions/13267/how-can-i-mimic-the-frame-selected-f-camera-move-z.html
Bounds CalculateBounds(GameObject go)
{
Bounds b = new Bounds(go.transform.position, Vector3.zero);
UnityEngine.Object[] rList = go.GetComponentsInChildren(typeof(Renderer));
foreach (Renderer r in rList)
{
b.Encapsulate(r.bounds);
}
return b;
}
public Vector3 FocusCameraOnGameObject(Camera c, GameObject go)
{
Bounds b = CalculateBounds(go);
Vector3 max = b.size;
// Get the radius of a sphere circumscribing the bounds
float radius = max.magnitude / 2f;
// Get the horizontal FOV, since it may be the limiting of the two FOVs to properly encapsulate the objects
float horizontalFOV = 2f * Mathf.Atan(Mathf.Tan(c.fieldOfView * Mathf.Deg2Rad / 2f) * c.aspect) * Mathf.Rad2Deg;
// Use the smaller FOV as it limits what would get cut off by the frustum
float fov = Mathf.Min(c.fieldOfView, horizontalFOV);
float dist = radius / (Mathf.Sin(fov * Mathf.Deg2Rad / 2f));
Debug.Log("Radius = " + radius + " dist = " + dist);
c.transform.localPosition = new Vector3(c.transform.localPosition.x, c.transform.localPosition.y, -dist);
if (c.orthographic)
c.orthographicSize = radius;
// Frame the object hierarchy
c.transform.LookAt(b.center);
var pos = new Vector3(c.transform.localPosition.x, c.transform.localPosition.y, dist);
return pos;
}