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.htmlhtml
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中得到鼠標基於屏幕座標系的點擊位置canvas
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.htmlui