2015-06-17 148 views
2

有誰知道如何在Unity中將像素座標轉換爲UI座標,反之亦然?比方說,我想用鼠標點擊屏幕上的某個地方,然後用戶界面圖像處於該點擊位置。如果我這樣做是行不通的:從像素座標轉換爲Unity中的UI座標

Image img = null // I assign it via the inspector 
void Update() 
{ 
    if(Input.GetMouseButtonDown(0)) 
    { 
     img.rectTransform.anchorPosition = Input.mousePosition; 
    } 
} 

回答

3
Image img = null // I assign it via the inspector 
void Update() 
{ 

     if(Input.GetMouseButtonDown(0)) 
    { 
     Vector2 point; 
     RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)img.rectTransform.parent, Input.mousePosition, canvasCamera, out point); 
     img.rectTransform.anchorPosition = point; 
    } 
} 
+0

完美。有效。謝謝。對於那些有這個問題的人來說:附加信息:UI元素的畫布必須處於Screen Space Camera模式。同樣作爲ScreenPointToLocalPointInRectangle函數的第三個參數使用畫布使用的相機。 – user3765498