【问题标题】:Position auto-scaled UI element with Camera.WorldToScreenPoint使用 Camera.WorldToScreenPoint 定位自动缩放的 UI 元素
【发布时间】:2018-09-10 23:56:54
【问题描述】:

我有一个Canvas。 我正在使用以下代码在场景中的 3D 对象上方创建一些 Text 元素:

Vector3 screenPos = Camera.main.WorldToScreenPoint(this.dices[x, z].transform.position);
screenPos.x -= 25;
screenPos.y += 10;
newScoreItem.GetComponent<RectTransform>().anchoredPosition = screenPos;

在 Android 上,我的 UI 元素很小,所以我将周围的 Canvas 的 UI 缩放模式设置为“随屏幕大小缩放”。

问题是我用上面的代码确定的位置与缩放画布的位置不匹配。我的 Text 元素已缩放,但位置完全错误。

我该如何解决这个问题?

正确的定位(在 Mac 上):

Scale with screen size(在 Android 上)的错误定位(屏幕外某处):

【问题讨论】:

  • “正确位置”和“错误位置”的屏幕截图会很有帮助。
  • 我添加了两个屏幕截图,但我怀疑它会有所帮助。

标签: unity3d


【解决方案1】:

你可以设置一个背景。

将所有内容设置为背景。

// Use this for initialization
void Start()
{
 resizeSprite();
}

void resizeSprite()
{
 SpriteRenderer bgSprite = GetComponent<SpriteRenderer>();
 float screenHeight = Camera.main.orthographicSize * 2;
 float screenWidth = screenHeight / Screen.height * Screen.width;
 transform.localScale = new Vector3(screenWidth / bgSprite.sprite.bounds.size.x,   screenHeight / bgSprite.sprite.bounds.size.y, 1);
}

aftar 改变了一切调整大小以设计分辨率。

【讨论】:

    【解决方案2】:

    首先检查文本“newScoreItem”的Anchors Min/Max:屏幕上的0,0点在左下角,因此Anchors Min/Max应该为0(左下角)。

    第二 - 你如何设置屏幕匹配模式很重要。 如果设置为匹配宽度或高度,您可以使用以下脚本:

        float refWidth = 800f; // reference resolution - width - set in Canvas Scaler 
        float refHeight = 480f; // reference resolution - height - set in Canvas Scaler
        bool matchWidth = true; //true if screen match mode is set to match the width, 
                        //false if is set to match the height
        Vector3 screenPos = Camera.main.WorldToScreenPoint(this.dices[x,y].transform.position);
        if (matchWidth) {
            screenPos.x *= refWidth / Screen.width;
            screenPos.y *= refWidth / Screen.width;
        } else {
            screenPos.x *= refHeight / Screen.height;
            screenPos.y *= refHeight / Screen.height;
        }
        screenPos.x -= 25f;
        screenPos.y += 10f;
        newScoreItem.GetComponent<RectTransform>().anchoredPosition = screenPos;
    

    它对我有用,虽然也许有更简单的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      相关资源
      最近更新 更多