標籤:inpu epo 圖片 pre cal rect ESS DPoS 起點
螢幕座標(Input.mousePosition)轉換UI座標需要瞭解到的知識點
1:螢幕座標的起點位置 左下角為(0,0)點,右上方為(Screen.width,Screen.height)
2:UI座標的起點位置 螢幕中心點
方法1
Vector2 uisize = canvas.GetComponent<RectTransform>().sizeDelta;//得到畫布的尺寸 Vector2 screenpos = Input.mousePosition; Vector2 screenpos2; screenpos2.x = screenpos.x - (Screen.width / 2);//轉換為以螢幕中心為原點的螢幕座標 screenpos2.y = screenpos.y - (Screen.height / 2); Vector2 uipos;//UI座標 uipos.x = screenpos2.x* (uisize.x / Screen.width);//轉換後的螢幕座標*畫布與螢幕寬高比 uipos.y = screenpos2.y * ( uisize.y / Screen.height);
方法2
Vector3 worldPos=Camera.main.ScreenToWorldPoint(Input.mousePosition);//螢幕座標轉換全局座標 Vector2 uiPos = canvas.transform.InverseTransformPoint(worldPos);//全局座標轉換位本地座標
方法3
Vector2 uipos = Vector3.one;RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, Camera.main, out uipos);//將螢幕空間點轉換為RectTransform的局部空間中位於其矩形平面上的位置。//cam參數是與螢幕點關聯的攝像機。對於Canvas中設定為Screen Space - Overlay模式的RectTransform,cam參數應為null。//當在提供PointerEventData對象的事件處理常式中使用ScreenPointToLocalPointInRectangle時,可以使用PointerEventData.enterEventData(用於懸停功能)或PointerEventData.pressEventCamera(用於單擊功能)擷取正確的網路攝影機。這將自動為給定事件使用正確的相機(或null)。
螢幕座標(Input.mousePosition)轉換UI座標