【问题标题】:Draw a Rect using GUI.DrawTexture on exactly gameobject's position Unity使用 GUI.DrawTexture 在游戏对象的位置 Unity 上绘制一个 Rect
【发布时间】:2016-07-22 17:29:51
【问题描述】:

我必须使用 "GUI.DrawTexture(new Rect..." 函数​​在我的屏幕上绘制一个矩形(实际上,它是我从https://www.assetstore.unity3d.com/en/#!/content/19972 得到的一个渐变 GUI 栏,但它的深处只是一个矩形) . 我想在我屏幕上的游戏对象旁边做。

问题是:矩形的坐标似乎与游戏对象的坐标不同(我在网上搜索过,我猜是真的)。我尝试了以下函数将游戏对象的位置转换为矩形的坐标,但仍然没有运气:

 public Vector2 WorldToGuiPoint(Vector2 position)
     {
         var guiPosition = Camera.main.WorldToScreenPoint(position);
         guiPosition.y = Screen.currentResolution.height - guiPosition.y;

         return guiPosition;
     }

我最好的一击是我这样做的时候:

Vector3 gameObjectsPosition = Camera.main.WorldToScreenPoint(gameObject);

然后当我想绘制矩形时:

GUI.DrawTexture(new Rect(gameObjectsPosition.x, Screen.height - gameObjectsPosition.y, Background.width * ScaleSize, Background.height * ScaleSize), Background);

但是,Rect 仍然不在游戏对象的确切位置上。 x 是对的,但 y 不是,当我搜索互联网时,他们说我只需要在绘制 Rect 时执行“Screen.height - gameObjectsPosition.y”。它对我不起作用,y 仍然是错误的。

我应该怎么做才能在屏幕上当前游戏对象旁边创建一个矩形(例如,如果游戏对象的位置是 x = -401 和 y = -80,我希望它在 y=-80 和 x= -300)

【问题讨论】:

    标签: unity3d unity5 rect gameobject


    【解决方案1】:

    您需要使用Screen.height 而不是 Screen.currentResolution.height

    using UnityEngine;
    using System.Collections;
    public class GuiPosition : MonoBehaviour 
    {
    
        public Vector2 WorldToGuiPoint(Vector3 GOposition)
        {
            var guiPosition = Camera.main.WorldToScreenPoint(GOposition);
            // Y axis coordinate in screen is reversed relative to world Y coordinate
            guiPosition.y = Screen.height - guiPosition.y;
    
            return guiPosition;
        }
    
        void OnGUI() 
        {
            var guiPosition = WorldToGuiPoint(gameObject.transform.position);
            var rect = new Rect(guiPosition, new Vector2(200, 70));
            GUI.Label(rect, "TEST");
        }
    }
    

    我刚刚测试了将 MonoBehaviour 附加到 Cube GameObject 并且它可以工作

    【讨论】:

    • 感谢您的帮助,但对我来说仍然没有用。我认为这是因为我必须使用从assetstore.unity3d.com/en/#!/content/19972 获得的 GuiBarScript.cs,所以我使用带有背景的 GUI.Drawtexture 而不是常规的 Rect,例如:GUI.DrawTexture(new Rect(gameObjectsPosition.x, Screen .height - gameObjectsPosition.y, Background.width * ScaleSize, Background.height * ScaleSize), Background);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多