UGUI 將2DUI和場景中的3d物體關聯,跟隨物體移動

項目中經常會用到 UI 和場景的物體關聯,之前的做法是將UI做成3D的,即將Canvas畫布的屬性 RenderMode 設置位WorldSpace。
但是這有一個缺點 攝像機移動或者攝像機縮放場景 ,導致UI字體會看不清。爲了解決這個問題,就用到了遊戲裏的人物頭頂血條。
主要的關鍵點是:
1.將3D物體的世界位置轉換位屏幕座標位置 Camera.main.WorldToScreenPoint
2.將UI的RectTransform 設置轉換後的屏幕座標,可以這轉換後屏幕座標基礎上添加x,y的偏移量

public class HealthBar : MonoBehaviour {

    public float xOffset;
    public float yOffset;
    public RectTransform recTransform;

    void Update()
    {
        if (recTransform==null)
        {
            return;
        }
        Vector2 player2DPosition = Camera.main.WorldToScreenPoint(transform.position);
        recTransform.position = player2DPosition + new Vector2(xOffset, yOffset);

        //血條超出屏幕就不顯示  
        if (player2DPosition.x > Screen.width || player2DPosition.x < 0 || player2DPosition.y > Screen.height || player2DPosition.y < 0)
        {
            recTransform.gameObject.SetActive(false);
        }
        else
        {
            recTransform.gameObject.SetActive(true);
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章