牛骨文教育服务平台(让学习变的简单)
博文笔记

Unity3d gui自适应屏幕

创建时间:2016-09-27 投稿人: 浏览次数:2311
用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的位置和大小都按照比例缩放了  很简单
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。