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;
    }

}

完成

相关推荐
星空露珠5 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
中国搜索直付通7 小时前
棋牌游戏支付与防沉迷:二级商户如何构建“免疫系统”
游戏
2601_962924767 小时前
遗忘之海手游战术家怎么玩 遗忘之海手游战术家玩法攻略
游戏
雅客李8 小时前
2026年第三季度云手机实测 游戏多开挂机托管三维度数据公开
游戏·智能手机
xcLeigh10 小时前
Unity基础:创建你的第一个游戏物体——Cube、Sphere与基本3D物体
游戏·3d·unity·教程
ellis197011 小时前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#
_Tenk_11 小时前
自研开源小工具 SwitchDeck:一键切换分辨率/刷新率/音频输出(附 WinForms 高 DPI 踩坑实录)
游戏·分辨率·cs2·看电影·一键切换·音响耳机音频·州瓦go
HH‘HH21 小时前
Unity通过OPC UA工业协议连接工业设备实战指南
unity·游戏引擎
め.1 天前
定点数运算库
算法·unity