【问题标题】:Position object on screen in different resolutions / aspect ratios (orthographic)以不同的分辨率/纵横比(正交)在屏幕上定位对象
【发布时间】:2015-05-28 03:42:44
【问题描述】:

说实话,我对 Unity 中的世界、屏幕和视口坐标感到很迷茫。
我的问题很简单:在 2d 游戏中,无论分辨率和屏幕纵横比如何,如何将对象放置在左下角?

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    你的描述有点模糊,但我认为你在谈论这个:

    Vector3 screenPos = new Vector3(x,y,z);
    
    camera.ScreenToWorldPoint(screenPos);
    

    附带说明,2D Unity 有特定的算法,也可以搜索。

    对于正交检查这个统一空间可能会帮助你:

    http://answers.unity3d.com/questions/501893/calculating-2d-camera-bounds.html

    【讨论】:

    • 说实话我不太了解你的代码。假设我们有一个名为 Player 的对象。无论长宽比和分辨率如何,如何将其位置更改为左下角?
    • @BanzaiTokyo,首先要确定的是,您使用的是正交相机投影还是透视?
    【解决方案2】:

    我看到没有人跟进此事。让我们先弄清楚一些术语: Camera.main = 正在查看您的游戏世界的主摄像机 “游戏世界”=您绘制的整个游戏地图 世界点 = 游戏世界中一个绝对的、独特的位置。可以是 2D 或 3D (x,y,z) 屏幕点 = 屏幕上像素的 2D x,y 位置

    因此,当您想要放置一个对象(即转换其位置)时,您真正要做的是将其放置在游戏世界中的某个位置。如果相机碰巧正在看世界中的那个位置,那么它将出现在屏幕上。

    要确定世界的哪些部分当前在屏幕上,您必须将屏幕点转换为世界点。所以...假设您的对象的大小是 20x20,试试这个:

    //Attach this script to the item you want "pinned" to the bottom, left corner of the screen
    void Update() {
      //fetch the rectangle for the whole screen
      Rect viewportRect = Camera.main.pixelRect; //again, this has nothing to do with the World, just the 2D screen "size", basically
    
      //now, let's pick out a point on the screen - bottom, left corner - but leave room for the size of our 20x20 object
      Vector3 newPos = new Vector3(viewportRect.xMin + 20, Camera.main.pixelHeight - 20, 0);
    
      //now calculate where we need to place this item in the World so that it appears in our Camera's view (and, thus, the screen)
      this.transform.position = Camera.main.ScreenToWorldPoint(newPos);
    }
    

    我 98% 确定这是所有准确信息,但如果有人发现错误,请指出。

    【讨论】:

    • 这看起来几乎是正确的。我对 Camera.main.pixelRect 的理解是它在整个屏幕上可见的矩形。这不一定是屏幕的全尺寸,也不能保证从屏幕的左下角开始。你最好只使用 Screen.Width/Screen.Height 并使用百分比偏移而不是绝对值来更好地处理多个分辨率。
    猜你喜欢
    • 2021-04-23
    • 2012-10-06
    • 2011-10-27
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多