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

}

完成

相关推荐
mxwin6 小时前
Unity Shader 深度写入与关闭ZWrite Off · 半透明排序 · 粒子穿插
unity·游戏引擎·shader
张老师带你学7 小时前
宇宙飞船完整Unity项目
科技·游戏·unity·游戏引擎·模型
mxwin7 小时前
Unity URP 下的流体模拟 深入解析 Navier-Stokes 方程与浅水方程的数学原理
unity·游戏引擎
mxwin11 小时前
Unity Shader 深度重建世界坐标
unity·游戏引擎·shader
德迅云安全-小潘12 小时前
游戏行业网络安全态势分析与应对
安全·web安全·游戏
雪儿waii12 小时前
Unity 中继承(父类子类)用法详解
unity·游戏引擎
总写bug的程序员12 小时前
用 AI 蒸馏球员的思维操作系统:qiuyuan-skill 技术解析
人工智能·unity·游戏引擎
penngo15 小时前
用 Claude Code 开发多人猜拳游戏:Go 语言实践
开发语言·游戏·golang
Neolnfra15 小时前
在 WorkBuddy 上开发游戏:我的实战经验分享
游戏·游戏机·workbuddy·开发游戏
mxwin15 小时前
Unity Shader 预乘 Alpha 完全指南 解决半透明纹理边缘黑边问题,让你的 UI 渲染更干净
unity·游戏引擎