0
点赞
收藏
分享

微信扫一扫

根据视野内物体的动态调整相机的拍摄范围

兮城 2022-02-16 阅读 80

仅对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,以便封装这些边界。
            bounds.Encapsulate(col.bounds);
        }

        //通过沿每一侧将边界的 size 增加 /amount/,扩展这些边界。
        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);
    }
}
举报

相关推荐

0 条评论