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

}

完成

相关推荐
SmalBox7 小时前
【光照】[自发光Emission]以UnityURP为例
unity·渲染
摸鱼的春哥1 天前
10年3次大失败,他从“罪人”输成了中年人的“白月光”
游戏
SmalBox2 天前
【光照】Unity中的[经验模型]
unity·渲染
萘柰奈2 天前
Unity学习----【进阶】TextMeshPro学习(三)--进阶知识点(TMP基础设置,材质球相关,两个辅助工具类)
学习·unity
Yasin Chen2 天前
Unity UI坐标说明
ui·unity
陈言必行2 天前
Unity 性能优化 之 编辑器创建资源优化( 工作流 | 场景 | 预制体)
unity·编辑器·游戏引擎
1uther2 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
2501_918126912 天前
用html5写一个flappybird游戏
css·游戏·html5
死也不注释2 天前
【Unity UGUI 交互组件——Slider(7)】
unity·游戏引擎·交互
程序猿多布2 天前
XLua教程之热补丁技术
unity·c#·lua·xlua