前言
之前開發遇到過這樣一個情況
UICanvas的相機是正交相機
場景相機也是正交相機 因爲是2D遊戲
出現的問題是:當創建UI血條想讓血條跟隨 3維場景下的某個物體 出現位置偏差
解決方式
第一種情況
UICanvas的相機是正交相機
場景相機也是正交相機
把動態創建出來需要跟隨3D物體的UI的父級錨點 鉚釘在左下角
這樣再把3D物體的座標轉換到屏幕座標
Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(Camera.main, Target.position);
rect_tran.anchoredPosition = screenPos;
第二種情況
UI是正交相機 場景是透視相機
如果想讓UI創建出來跟隨3維物體,那麼以上做法也可以 。
第三種情況
UI是正交相機 場景是透視相機
可以不用設置創建出來的UI父級錨點 只針對於場景相機是透視相機 UI相機隨意
需要把3維座標轉屏幕座標 再把屏幕空間上的點轉換爲位於給定RectTransform平面上的世界空間中的位置
public void setPostion()
{
if (rect_tran == null) rect_tran = GetComponent<RectTransform>();
Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(Camera.main, Target.position);
rect_tran.anchoredPosition = screenPos;
Vector3 pos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rect_tran, screenPos, Camera.main, out pos))
{
transform.position = pos ;
}
}