【Unity】RectTransformUtility.ScreenPointToLocalPointInRectangle

目录

简介

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

一、参数

csharp 复制代码
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 方法的示例代码:

csharp 复制代码
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 交互和布局控制。

相关推荐
Jason?132 小时前
Unity基于Recoder的API写了一个随时录屏的工具
java·unity·游戏引擎
weixin_424294678 小时前
Unity 调节 Rigidbody2D 响应速度的解决方案【资料】
unity·游戏引擎
霜绛8 小时前
Unity笔记(三)——父子关系、坐标转换、Input、屏幕
笔记·学习·unity·游戏引擎
污领巾21 小时前
虚幻GAS底层原理解剖六 (Target)
游戏引擎·虚幻
zxc2446039341 天前
gpu instancer crowd 使用自定义材质并且只修改单个物体的材质参数
unity·材质
伽蓝_游戏1 天前
UGUI源码剖析(3):布局的“原子”——RectTransform的核心数据模型与几何学
ui·unity·架构·c#·游戏引擎·游戏程序·几何学
Kingsdesigner1 天前
游戏开发流程革命:我用Substance插件,在UE5内实现材质的实时“创世纪”
游戏·adobe·ue5·游戏引擎·游戏开发·设计师·substance 3d
污领巾1 天前
虚幻GAS底层原理解剖七 (ASC)
游戏引擎·php·虚幻
污领巾1 天前
虚幻GAS底层原理解剖四 (TAG)
游戏引擎·虚幻