【Unity3D】透视相机自动渲染包围物体组,如何设置相机的位置?

目前在做大量三维模型预览的交互的功能,希望自动根据模型的位置和包围盒的大小自动调节相机与模型的距离,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的简单记录,后续再调整。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值