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

}

完成

相关推荐
一只大头猿8 小时前
虚拟化版|红色沙漠|官方简体中文
游戏
笨鸟先飞的橘猫9 小时前
游戏后端分布式学习——开篇
分布式·学习·游戏
郝学胜-神的一滴10 小时前
中级OpenGL教程 022:探秘三维世界的血脉传承——物体父子关系与矩阵递归奥义
c++·线性代数·unity·矩阵·游戏引擎·unreal engine·opengl
Jiamiren11 小时前
WEEX Labs 周度观察:AI 基础设施的“权力游戏”与硬核变现时代
人工智能·游戏
YakSue1 天前
游戏项目中的程序化生成(PCG):五层工作的耦合问题
游戏
weixin_424294671 天前
Unity的测试Edit Mode和Play Mode,有什么区别?
unity
国际学术会议-杨老师1 天前
2026年游戏美学、动画生成与色彩科学国际会议(GEAAC 2026)
游戏·动画·色彩科学
qizayaoshuap1 天前
# [特殊字符] 猜数字 — 鸿蒙ArkTS游戏逻辑与交互反馈系统设计
游戏·华为·harmonyos
玖玥拾1 天前
Unity 3D 笔记(八)ScrollRect 滚动视图、NavMesh 自动寻路系统
笔记·3d·unity