The Unity camera zooms in to an object

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour {
    public GameObject[] objs;
    public Camera mCamera;
    int index = 0;
	
	// Update is called once per frame
	void Update () {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            GameObject obj = objs[index % objs.Length];
            MeshRenderer mr = obj.GetComponent<MeshRenderer>();

            //物体最大长度
            float a = mr.bounds.size.magnitude;

            //物体相机的距离
            float b = Vector3.Distance(mCamera.transform.position, obj.transform.position);

            //视场角,单位为度
            float angle = Mathf.Rad2Deg * Mathf.Atan(0.5f * a / b);            
            mCamera.fieldOfView = 2.0f * angle;

            //正对着物体
            mCamera.transform.LookAt(mr.bounds.center);

            index++;
        }		
	}
}

 The object was originally placed like this

Press the space bar to zoom to an object in turn 

 

 

Guess you like

Origin blog.csdn.net/zouxin_88/article/details/123610954