zoukankan      html  css  js  c++  java
  • 【Unity3d】使GUI适应屏幕分辨率

    本文转自:xlincuts的博客,如果侵权,请及时告诉我及时删除!                        

                            【Unity3d】使GUI适应屏幕分辨率

    用Unity开发移动平台的游戏  不可避免的会遇到屏幕分辨率的问题  

    不同的分辨率上会使得原本正常的UI变得乱七八糟  

    我们知道  在Unity中可以拿一个plane作为背景 UI则是绘制在离摄像机最近的位置  可以认为是绘制在摄像机上的

    因此分辨率的不同会导致UI的位置和大小出现错误

    我们完全可以用一个plane去模拟button  并将它放在世界空间中  这样虽然可以解决位置和大小的问题  但是所带来的问题也一大堆并难于维护

    因此我们需要根据屏幕的大小去按比例缩放UI

    假如原本有个按钮是这样,并且当前的480x854分辨率下没问题,如果改成600x1024或者其他的分辨率,便会发现位置和大小都不正确了

    复制代码
    function OnGUI ()
    {
    if (GUI.Button(Rect(Screen.width - 200, Screen.height - 100, 64, 64), "Start"))
    {
    // dosomething
    }
    }
    复制代码

    于是我们按比例去移动和缩放UI

    复制代码
    // original screen size
    var m_fScreenWidth : float = 480;
    var m_fScreenHeight : float = 854;

    // scale factor
    var m_fScaleWidth : float;
    var m_fScaleHeight : float;

    function Awake ()
    {
    m_fScaleWidth = parseFloat(Screen.width)/m_fScreenWidth;
    m_fScaleHeight = parseFloat(Screen.height)/m_fScreenHeight;
    }

    function OnGUI ()
    {
    if (GUI.Button(Rect(Screen.width - 200 * m_fScaleWidth , Screen.height - 100 * m_fScaleHeight , 64 * m_fScaleWidth , 64 * m_fScaleHeight ), "Start"))
    {
    // dosomething
    }
    }
    复制代码

    若UI控件较多的时候,对每一个都去控制大小显然没必要

    则使用矩阵实现

    GUI.matrix = Matrix4x4.TRS (Vector3(0, 0, 0), Quaternion.identity, Vector3 (m_fScaleWidth, m_fScaleHeight, 1)); 

    这样就将button的位置和大小都按照比例缩放了  很简单

  • 相关阅读:
    PostgerSQL 回收表空间,查看占用磁盘大小
    为 Docker 添加阿里云的镜像地址
    Docker 常用命令
    CentOS 7 安装 Docker
    kafka-常用脚本2
    Nginx 端口被占用(0.0.0.0:443 failed (98: Address already in use))
    nginx: [error] open() "/var/run/nginx.pid" failed (2: No such file or directory)
    检查Nginx 配置文件出否有问题
    Python2 安装虚拟环境
    记录 | 程序员技术博客平台推荐和选取
  • 原文地址:https://www.cnblogs.com/alongu3d/p/3060239.html
Copyright © 2011-2022 走看看