//摄影机追踪多个物体public class CameraCtr : MonoBehaviour{ //[SerializeReference] public Transform []GameObjects; private Vector3 offSet; private Camera upCamera; private void Start() { Vector3 centerPoint = CenterPoint(); offSet = transform.position - centerPoint; } //获取所有物体的中心点 private Vector3 CenterPoint() { Vector3 point = new Vector3 (); foreach (Transform GameObject in GameObjects) { point += GameObject.position; } point = point / GameObjects.Length; return point; } //摄像机控制 private void LateUpdate() { Vector3 point = CenterPoint(); transform.position = point + offSet; upCamera.orthographicSize = GetScreenSize(); } //获取屏幕的最大尺寸 private float GetScreenSize() { Vector3 centerPoint = CenterPoint(); Vector3 centerPointAtCamera = transform.InverseTransformPoint(centerPoint); //将以世界坐标转换为以Camera为原点的坐标 float maxSize = 0; foreach (Transform GameObject in GameObjects) { Vector3 gameObjectAtCamera = transform.InverseTransformPoint(GameObject.position );//将以世界坐标转换为以Camera为原点的坐标 Vector3 distance = gameObjectAtCamera - centerPointAtCamera;//获取摄影机原点下的坦克与中心点的距离 maxSize = Mathf.Max(maxSize ,Mathf .Abs (distance .y ));//获取y方向的最大值 maxSize = Mathf.Max(maxSize, Mathf.Abs(distance.x))/upCamera .aspect ;//获取x方向的最大值 } return maxSize; }}