1. //摄影机追踪多个物体
    2. public class CameraCtr : MonoBehaviour
    3. {
    4. //[SerializeReference]
    5. public Transform []GameObjects;
    6. private Vector3 offSet;
    7. private Camera upCamera;
    8. private void Start()
    9. {
    10. Vector3 centerPoint = CenterPoint();
    11. offSet = transform.position - centerPoint;
    12. }
    13. //获取所有物体的中心点
    14. private Vector3 CenterPoint()
    15. {
    16. Vector3 point = new Vector3 ();
    17. foreach (Transform GameObject in GameObjects)
    18. {
    19. point += GameObject.position;
    20. }
    21. point = point / GameObjects.Length;
    22. return point;
    23. }
    24. //摄像机控制
    25. private void LateUpdate()
    26. {
    27. Vector3 point = CenterPoint();
    28. transform.position = point + offSet;
    29. upCamera.orthographicSize = GetScreenSize();
    30. }
    31. //获取屏幕的最大尺寸
    32. private float GetScreenSize()
    33. {
    34. Vector3 centerPoint = CenterPoint();
    35. Vector3 centerPointAtCamera = transform.InverseTransformPoint(centerPoint); //将以世界坐标转换为以Camera为原点的坐标
    36. float maxSize = 0;
    37. foreach (Transform GameObject in GameObjects)
    38. {
    39. Vector3 gameObjectAtCamera = transform.InverseTransformPoint(GameObject.position );//将以世界坐标转换为以Camera为原点的坐标
    40. Vector3 distance = gameObjectAtCamera - centerPointAtCamera;//获取摄影机原点下的坦克与中心点的距离
    41. maxSize = Mathf.Max(maxSize ,Mathf .Abs (distance .y ));//获取y方向的最大值
    42. maxSize = Mathf.Max(maxSize, Mathf.Abs(distance.x))/upCamera .aspect ;//获取x方向的最大值
    43. }
    44. return maxSize;
    45. }
    46. }