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

}

完成

相关推荐
珍猪吃饲料21 小时前
消息丢了、重复消费了,MQ 这套账该怎么算
游戏
芝麻粒儿1 天前
Scratch少儿编程案例-多人联机与IO游戏(1)
游戏·青少年编程·scratch·少儿编程
赤生云电竞2 天前
云游戏边缘节点部署:机房选址与网络拓扑优化实践 —— 从80ms时延预算看节点落位与Spine-Leaf组网
服务器·游戏·spine
ellis19702 天前
Claude Code[二] 上下文相关的机制
unity·ai编程
武子康3 天前
AI通关了,游戏就算通过测试了吗?
人工智能·游戏·机器学习
张小姐的猫3 天前
【基于 WebSocket 的多用户网页五子棋】—— 游戏匹配对战设计
websocket·网络协议·游戏
zdr尽职尽责3 天前
Unity 3C 动画系统:从「蜘蛛网」到可维护的动画架构
unity·架构·游戏引擎
有度即时通3 天前
合规刚需下,游戏行业适合的内网通讯软件怎么选
游戏
芝麻粒儿3 天前
Scratch少儿编程案例-愤怒的小鸟(1)
游戏·青少年编程·scratch·少儿编程·编程猫
国家一级摸鱼选手3 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交