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

}

完成

相关推荐
世洋Blog1 小时前
H5游戏-Canvas绘制与JS基础
javascript·游戏·h5·canvas
jtymyxmz2 小时前
《Unity Shader》14.1 卡通风格的渲染
unity·游戏引擎
前端不太难2 小时前
HarmonyOS 游戏里的“假异步”,为什么会卡
游戏·状态模式·harmonyos
子春一3 小时前
Flutter for OpenHarmony:构建一个沉浸式 Flutter 掷骰子游戏,深入解析动画控制器、CustomPaint 自定义绘制与状态同步
flutter·游戏
天人合一peng3 小时前
unity获得和修改button的text(TMP)
java·前端·unity
dzj202111 小时前
Unity中使用LLMUnity遇到的问题(三)——如何配置和使用知识库
unity·llmunity·知识库大模型
Elastic 中国社区官方博客12 小时前
使用 Discord 和 Elastic Agent Builder A2A 构建游戏社区支持机器人
人工智能·elasticsearch·游戏·搜索引擎·ai·机器人·全文检索
Clank的游戏栈12 小时前
Unity自动化美术资源校验工具(模型/材质规范检测)技术详解
unity·自动化·材质
njsgcs19 小时前
枪战游戏“棋盘化”价值建模 强化学习或rag
游戏
Sator119 小时前
Unity烘焙光打包后光照丢失问题
unity·光照贴图