仅对2D游戏下的正交相机适用
using UnityEngine;
public class OrthogonalCamera2D : MonoBehaviour
{
[Header("四周边框留白")] public float _buffer = 0;
private Camera _cam;
private void Awake()
{
_cam = GetComponent<Camera>();
}
private void Update()
{
if (_cam == null) return;
var (center, size) = CalculateOrthoSize();
_cam.transform.position = center;
_cam.orthographicSize = size;
}
private (Vector3 center, float size) CalculateOrthoSize()
{
var bounds = new Bounds();
foreach (var col in FindObjectsOfType<Collider2D>())
{
bounds.Encapsulate(col.bounds);
}
bounds.Expand(_buffer);
var vertical = bounds.size.y;
var horizontal = bounds.size.x * _cam.pixelHeight / _cam.pixelWidth;
Debug.Log($"bounds.size {bounds.size}");
Debug.Log(
$" _cam.pixelHeight / _cam.pixelWidth = {_cam.pixelHeight} / {_cam.pixelWidth} = {_cam.pixelHeight / (float) _cam.pixelWidth}");
var size = Mathf.Max(horizontal, vertical) * 0.5f;
var center = bounds.center + new Vector3(0, 0, -10);
return (center, size);
}
}
|