public static bool ScreenPointToLocalPointInRectangle(RectTransform rect, Vector2 screenPoint, Camera cam, out Vector2 localPoint);
rect: 對應的 RectTransform 的引用
screenPoint: 位置,基於屏幕坐標系
cam: 相機的引用,如果Canvas的Render Mode 為 Screen Space - Camera 模式,則需要填入 Render Camera 對應的引用
localPoint: rect 本地坐標系下的坐標(原點(0,0)位置受Anchor的影響)
參考:
https://docs.unity3d.com/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html
using UnityEngine; using UnityEngine.UI; using System.Collections; using UnityEngine.EventSystems; public class GlobalTest : MonoBehaviour { public Canvas canvas; Text uiText; RectTransform canvasRect; RectTransform textRect; void Start() { uiText = canvas.GetComponentInChildren<Text>(); canvasRect = canvas.GetComponent<RectTransform>(); textRect = uiText.GetComponent<RectTransform>(); Debug.Log(textRect.anchoredPosition); } void Update() { if (Input.GetMouseButtonUp(0)) { Vector2 outVec; if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect,Input.mousePosition,null,out outVec)) { Debug.Log("Setting anchored positiont to: " + outVec); textRect.anchoredPosition = outVec; } } } }
參考:
https://forum.unity.com/threads/issues-with-recttransformutility-screenpointtolocalpointinrectangle.437246/
再說一句
也可以從UGUI的EventSystem中獲得鼠標基於屏幕坐標系的點擊位置
public void OnPointerDown(PointerEventData pointerEventData) { //Output the name of the GameObject that is being clicked Debug.Log(name + "Game Object Click in Progress"); }
參考:
https://docs.unity3d.com/ScriptReference/EventSystems.IPointerDownHandler.html