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

}

完成

相关推荐
!chen9 小时前
Unity颜色曲线ColorCurves
unity·游戏引擎
B0URNE9 小时前
【Unity基础详解】(4)Unity核心类:MonoBehaviour
unity·游戏引擎
AA陈超14 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-29 属性信息委托
c++·游戏·ue5·游戏引擎·虚幻
AA陈超16 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-31 映射标签到属性
c++·游戏·ue5·游戏引擎·虚幻
小时候的阳光16 小时前
Cocos Creator 和 Unity 3D 编辑界面字体样式大小调整
unity·cocos2d·字体大小
ellis197016 小时前
Lua代码混淆-Prometheus方案教程
unity·lua
leafff12317 小时前
AI研究:轻量模型和专用模型在算力优化上的差异对游戏制作的效率和质量有何影响?
人工智能·游戏
Howard在远程17 小时前
[编程农场][The Farmer Was Replaced]——Bones/Dinasour
python·游戏
EQ-雪梨蛋花汤18 小时前
【MRTK3踩坑记录】Unity 2022 中 MRTK3 Input Simulator 无法使用 WASD 控制相机的完整排查记录
数码相机·unity·游戏引擎
星夜泊客1 天前
Unity 游戏开发中的防御性编程与空值处理实践
unity·设计模式·游戏引擎