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

本文探讨如何在2D游戏中根据视野内的动态物体来适配正交相机的拍摄范围,确保游戏体验。内容适用于使用Unity进行开发的2D游戏场景。
摘要由CSDN通过智能技术生成

仅对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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值