Unity:2D游戏设置相机orthographicSize

目录

[根据设备分辨率动态设置相机 orthographicSize](#根据设备分辨率动态设置相机 orthographicSize)


根据设备分辨率动态设置相机 orthographicSize

  • 2d游戏里面相机的Orthan.size确定的是高度,宽度是按照屏幕的宽高比计算出来的
  • cameraWidthSize = camera.Orthographic.size*(Screen.Width/Screen.height)
  • 我在游戏里设置的 开发分辨率是1080*1920
  • 所以我在原先Y=1920情况下 Camera设置的orthographicSize=10,可以恰好把图片横向全部展示
  • 如下

但是导出apk安装到手机上的时候 我的手机分辨率是1080*2440

  • 这个时候用unity用10来计算
  • 10*(Screen.Width/Screen.height)
  • 就会把宽度变小了
  • 但是到了手机里就变成了这样

所以需要按照开发的尺寸(原先的宽)度来重新计算size ,挂在摄像机上

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraAdaper : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        SetCamera(GetComponent<Camera>());
    }

    float width = 1080;//开发分辨率x
    float height = 1920;//开发分辨率y

    //需要适配宽度
    public void SetCamera(Camera camera)
    {
        var realWidthSize = (camera.orthographicSize * (width / height));
        Debug.Log($"width_{Screen.width}-height_{Screen.height}");
        float val  = realWidthSize / ((float)Screen.width / (float)Screen.height);
        Debug.Log($"cameraSzie{val}");
        camera.orthographicSize = val;
    }

}

完成

相关推荐
wjql23 小时前
steam远程畅玩的方法 怎么远程玩steam游戏
游戏
wjql25 小时前
三角洲行动爆破模式玩法介绍 三角洲行动爆破模式怎么远程玩
游戏
劉宇雁6 小时前
C++ ASCII 3D无尽跑酷游戏
c++·游戏·3d
科技圈快迅20 小时前
鸿蒙游戏体验手册:四种能力从性能到玩法逐一解锁
游戏
wjql21 天前
绝区零诺姆配队推荐 绝区零诺姆怎么配队
游戏
河南花仙子科技1 天前
复盘蓄力精进迭代|花仙子科技召开 2026 年 Q2 季度复盘总结大会
科技·游戏
生活爱好者!1 天前
NAS还能玩游戏?部署一款 WebGL 3D 赛车小游戏
游戏·docker·容器·玩游戏
丁小未1 天前
基于MVVM框架的XUUI 扩展的UI管理系统教程
unity·mvvm·ui框架·xuui·ui管理器
丁小未2 天前
基于MVVM框架的XUUI HelloWorld 新手教程
unity·性能优化·c#·游戏引擎
丁小未2 天前
基于MVVM框架的XUUI MoreComplex案例
unity·c#