目前在做大量三维模型预览的交互的功能,希望自动根据模型的位置和包围盒的大小自动调节相机与模型的距离,maybe太简单了,一直没有找到现成砖来搬;故简单记录一下;
public Camera mainCamera;
public GameObject cube;
private float boundWidth;
private float boundDepth;
//这里的bound可以计算一个包围盒集合,我这里为了方便只计算了一个立方体的包围盒
private Bounds bound;
//此参数记录的是包围盒的中心距离包围盒顶的距离,(包围盒的高度的一半)
private float Padding=0.5f;
void Start()
{
bound = cube.GetComponent<Renderer>().bounds;
var x = bound.extents.x;
var z = bound.extents.z;
boundWidth = x* 2;
boundDepth = z* 2;
AdjustCameraPosition();
}
void AdjustCameraPosition()
{
float fov = mainCamera.fieldOfView;
float ratio = Screen.width / (float)Screen.height;
float FovTan = Mathf.Tan((fov / 2) * Mathf.Deg2Rad);
float fitwidthDis = ((boundWidth / ratio) / 2) /FovTan;
float fitHeightDis = (boundDepth / 2) / FovTan;
mainCamera.transform.position = bound.center + new Vector3(0, Mathf.Max(fitHeightDis, fitwidthDis)+Padding,0);
mainCamera.transform.rotation = Quaternion.Euler(90, 0, 0);
}
一个demo的简单记录,后续再调整。