Unity3d 使用Camera.WorldToScreenPoint定位自动缩放的UI元素

Unity3d 使用Camera.WorldToScreenPoint定位自动缩放的UI元素,unity3d,Unity3d,我有一张画布。 我正在使用以下代码在场景中的3D对象上方创建一些文本元素: Vector3 screenPos = Camera.main.WorldToScreenPoint(this.dices[x, z].transform.position); screenPos.x -= 25; screenPos.y += 10; newScoreItem.GetComponent<RectTransform>().anchoredPosition = screenPos; Vecto

我有一张
画布
。 我正在使用以下代码在场景中的3D对象上方创建一些
文本
元素:

Vector3 screenPos = Camera.main.WorldToScreenPoint(this.dices[x, z].transform.position);
screenPos.x -= 25;
screenPos.y += 10;
newScoreItem.GetComponent<RectTransform>().anchoredPosition = screenPos;
Vector3 screenPos=Camera.main.WorldToScreenPoint(这个.dices[x,z].transform.position);
屏幕位置x-=25;
屏幕位置y+=10;
newScoreItem.GetComponent().anchoredPosition=screenPos;
在Android上,我的UI元素很小,所以我将周围的Canvas`UI缩放模式设置为“随屏幕大小缩放”

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

我怎样才能解决那个问题

正确定位(在Mac上):

错误的定位(在屏幕外的某个地方),屏幕大小为
比例(在Android上):


首先检查文本“newScoreItem”的锚定最小/最大值:屏幕上的点0,0位于左下角,因此锚定最小/最大值应为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;
float refWidth=800f;//参考分辨率-宽度-在画布缩放器中设置
浮动参考高度=480f;//参考分辨率-高度-在画布缩放器中设置
布尔匹配宽度=真//如果屏幕匹配模式设置为与宽度匹配,则为true,
//如果设置为与高度匹配,则为false
Vector3 screenPos=Camera.main.WorldToScreenPoint(this.dices[x,y].transform.position);
如果(匹配宽度){
屏幕位置x*=参考宽度/屏幕宽度;
屏幕位置y*=参考宽度/屏幕宽度;
}否则{
屏幕位置x*=参考高度/屏幕高度;
屏幕位置y*=参考高度/屏幕高度;
}
屏幕位置x-=25f;
屏幕位置y+=10f;
newScoreItem.GetComponent().anchoredPosition=screenPos;

这对我来说很有用,不过也许有更简单的方法。你可以设置一个背景

将所有内容设置为背景

// 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);
}
//将其用于初始化
void Start()
{
resizeSprite();
}
void resizeSprite()
{
SpriteRenderer bgSprite=GetComponent();
浮动屏幕高度=Camera.main.orthographicSize*2;
浮动屏幕宽度=屏幕高度/屏幕高度*屏幕宽度;
transform.localScale=newvector3(屏幕宽度/bgSprite.sprite.bounds.size.x,屏幕高度/bgSprite.sprite.bounds.size.y,1);
}

在那之后,为了设计分辨率,所有的东西都改变了大小。

一个关于“正确位置”和“错误位置”的屏幕截图会很有帮助。我添加了两个屏幕截图,但我怀疑它是否有用。