Unity中UI跟随3D物体 即HUD效果

今天简单的测试了Unity中UI跟随3D物体,使用Unity版本:5.6.4。

首先想到的有两种思路:

1、第一种方法基于RectTransformUtility.ScreenPointToWorldPointInRectangle和 Camera.main.WorldToScreenPoint这两个方法

首先把3D物体坐标转换到屏幕坐标,然后在从屏幕坐标转换到UI坐标:

    public Transform target;   //3D物体
    public RectTransform image;    //跟随3D物体的UI
    public Canvas canvas;   //UI所在的canvas

    private Vector2 screenPos;
    private Vector3 mousePos;

    void Update()
    {
        screenPos = Camera.main.WorldToScreenPoint(target.position);

        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(image, screenPos, canvas.worldCamera, out mousePos))
        {
            image.position = mousePos;
        }
    }

此时 UI就实现了3D物体。

2、当我们实现了第一个方法,此时在想我们基于Camera.main.WorldToScreenPoint方法,获取到屏幕坐标,然后根据屏幕坐标和UI坐标不同计算出UI坐标。

屏幕空间以像素定义,屏幕左下为0,0,UI坐标0,0点在屏幕正中间,如果加上x和y轴偏移量,我们可以使用一下方法实现:

    public RectTransform rectBloodPos;
    public int offsteX = 0;
    public int offsetY = 60;
    private Vector2 screenPoint;
    private Vector2 currPos = new Vector2();

    void Update()
    {
        screenPoint = Camera.main.WorldToScreenPoint(this.gameObject.transform.position);

        currPos.x = screenPoint.x - Screen.width / 2 + offsteX;
        currPos.y = screenPoint.y - Screen.height / 2 + offsetY;

        rectBloodPos.anchoredPosition = currPos;//控制偏移量
    }

次方法也实现了HUD效果。

猜你喜欢

转载自blog.csdn.net/qq_26723085/article/details/81289717