【问题标题】:Unity - Can't center mini-map viewport rect inside center of the imageUnity - 无法在图像中心内居中迷你地图视口矩形
【发布时间】:2020-11-25 11:27:52
【问题描述】:

如何将图像位置转换为相机视口视图?

我有一个雷达,我使用相机在屏幕上显示该视口,但它仅适用于一组矩形,该矩形仅适用于我设置的一种类型的屏幕。

如何将此矩形与图像变换位置相匹配。因此,如果屏幕发生变化并且随着它移动,它周围的 ui 也会随之移动相机视图。

这是针对 iPhone XS Max (2688x1242) 的屏幕

我想要像overlayCamera.rect = transform.position这样的东西

这是我用来显示相机矩形的代码。

private void UpdateCameraViewportRect()
{
    float aspectRatio = (float)Screen.width / Screen.height;
    float desiredScreenWidth = 0.271f;
    float viewHeight = 0.831f;
    float viewWidth = 0.78f;

    float width = desiredScreenWidth;
    float height = width * aspectRatio;
    if (height > 1.0f)
    {
        height = 1.0f;
        width = height / aspectRatio;
    }
    
    //  Controls the position of the view
    overlayCamera.rect = new Rect(
        viewHeight - width, viewWidth - height,
        width, height
    );
    
    /*
    // Method 1 -> Does not work
    Vector3 p = overlayCamera.ViewportToWorldPoint(new Vector3(1, 1, overlayCamera.nearClipPlane));
    Debug.Log(p);

    // Method 2 -> Does not work
    Vector3 screenPos = overlayCamera.WorldToScreenPoint(overlayCamera.transform.position);
    float posx = screenPos.x - (width * 0.5f);
    float posy = screenPos.y - (height * 0.5f);
    Debug.Log(posx + " & " + posy);

    // Method 3 -> Does not work
    overlayCamera.rect = radarBorder.rectTransform.rect;
    */
}

如何将视口矩形置于金色边框图像的中心?

解决方案:改为创建 RenderTexture 并将其显示在 RawImage 中以在 UI 中移动。

【问题讨论】:

  • 我很想帮忙,但不太明白您要做什么,也许添加一些屏幕截图或图表会有所帮助。
  • @PeterHayman 对于我的 UI,我有一个边框的 UI 图像。我想将相机视口矩形放在 UI 图像中。小地图的相机视口将屏幕的视口视图除以宽度和高度。我想将该位置更改为 UI 图像位置的中心。我该怎么做?
  • 抱歉没用,请截图。
  • @PeterHayman 抱歉,我添加了一张图片,看看视口矩形如何不在图片的中心。

标签: c# unity3d


【解决方案1】:

好吧,我可能理解错了,但是看起来方法是根据屏幕的纵横比动态调整 UI。

最好在编辑器中正常布局 UI,并使用 Camera.aspect 强制 overlayCamera 的纵横比为 1:1:

void Start(){
    var cam = GetComponent<Camera>();
    cam.aspect = 1;
    cam.ResetAspect();
}

编辑:

虽然可以调整相机在屏幕上的渲染位置,但您可以看到它有点混乱。通常的做法是 render to a RenderTexture 并将其放在 UI 内的材质上。

【讨论】:

  • 谢谢,但我想要相反,我想将相机视口矩形调整为在图像内居中。
  • 在哪里可以找到 RenderTexture 的一些示例?听起来是个完美的主意。
  • RenderTexture 正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-09-21
  • 2013-05-04
  • 2023-01-01
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多