using UnityEngine;
using UnityEngine.EventSystems;
public class ScreenToUIConverter : MonoBehaviour
{
public RectTransform targetParentRect; // 目标UI父物体的RectTransform
void Update()
{
Vector2 mousePos = Input.mousePosition; // 获取鼠标位置(屏幕坐标)
Camera canvasCam = null; // 如果Canvas的渲染模式为Screen Space - Overlay,Camera设置为null
// 将屏幕坐标转换为UI坐标
Vector2 localPoint;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(targetParentRect, mousePos, canvasCam, out localPoint))
{
Debug.Log("UI坐标: " + localPoint);
}
}
}
另一种:
// 将屏幕坐标转换为世界坐标
Vector3 worldPoint = mCamera.ScreenToWorldPoint(new Vector3(screenPoint.x, screenPoint.y, mCamera.nearClipPlane));
// 将世界坐标转换为本地坐标
Vector3 localPoint = Root.transform.InverseTransformPoint(worldPoint);