天天看點

Unity中世界坐标到UGUI坐标的轉換(自适應分辨率)

首先拿到畫布的RectTransfrom以及主錄影機的引用。

public RectTransform canvasRectTransform;
public Camera mainCamera;
           

先将世界坐标轉換為螢幕坐标,再将它變換到以螢幕中心為原點,最後根據畫布大小進行縮放。

// 将世界坐标轉換為Ugui坐标
    public static Vector2 WorldToUgui(Vector3 position)
    {

        Vector2 screenPoint = mainCamera.WorldToScreenPoint(position);//世界坐标轉換為螢幕坐标
        Vector2 screenSize = new Vector2(Screen.width, Screen.height);
        screenPoint -= screenSize/2;//将螢幕坐标變換為以螢幕中心為原點
        Vector2 anchorPos = screenPoint / screenSize * canvasRectTransform.sizeDelta;//縮放得到UGUI坐标
        return anchorPos;
    }
           

這樣就可實作UI上的血條跟随人物移動這些效果了

Unity中世界坐标到UGUI坐标的轉換(自适應分辨率)

繼續閱讀