【Unity】RectTransformUtility.ScreenPointToLocalPointInRectangle

发布于:2025-08-10 ⋅ 阅读:(15) ⋅ 点赞:(0)

简介

RectTransformUtility.ScreenPointToLocalPointInRectangle 是 Unity 中的一个静态方法,用于将屏幕空间中的点转换为位于 RectTransform 矩形平面上的本地空间点。这个方法在处理 UI 元素时非常有用,特别是在需要将屏幕坐标转换为 UI 坐标的情况下。

一、参数

public static bool ScreenPointToLocalPointInRectangle(
	RectTransform rect,
	Vector2 screenPoint,
	Camera cam,
	out Vector2 localPoint
);

1、参数说明

  • rect: 要在其中查找点的 RectTransform。

  • screenPoint: 屏幕空间位置。

  • cam: 与屏幕空间位置关联的摄像机。对于设置为 Screen Space - Overlay 模式的 Canvas 中的 RectTransform,cam 参数应为 null。

  • localPoint: 输出参数,表示矩形变换本地空间中的点。

2、返回值

  • bool: 如果点击 RectTransform 平面,则无论点是否在矩形内,都返回 true。

二、使用示例

以下是一个使用 ScreenPointToLocalPointInRectangle 方法的示例代码:

public class Example : MonoBehaviour
{
    public RectTransform rectTransform;
    public Camera uiCamera;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Vector2 localPoint;
            Vector2 screenPoint = Input.mousePosition;

            bool isInside = RectTransformUtility.ScreenPointToLocalPointInRectangle(
            rectTransform, screenPoint, uiCamera, out localPoint);

            if (isInside)
            {
                Debug.Log("Local Point: " + localPoint);
            }
        }
    }
}

在这个示例中,当用户点击鼠标左键时,Input.mousePosition 获取屏幕空间中的鼠标位置,然后使用 ScreenPointToLocalPointInRectangle 方法将其转换为 rectTransform 的本地空间点,并输出到控制台。

三、注意事项

  • Canvas 模式:如果 Canvas 的渲染模式是 Screen Space - Overlay,则 cam 参数应设置为 null。

  • localPoint 参数:该参数对应的是 RectTransform.localPosition,而不是 RectTransform.anchoredPosition。

通过使用 ScreenPointToLocalPointInRectangle 方法,可以方便地将屏幕坐标转换为 UI 元素的本地坐标,从而实现更精确的 UI 交互和布局控制。


网站公告

今日签到

点亮在社区的每一天
去签到