屏幕坐標(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)。
