【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 交互和布局控制。

相关推荐
Ziegler Han44 分钟前
Unity入门:给Image添加图片
unity·游戏引擎
入目星河滚烫6 小时前
Unity避坑——继承了MonoBehaviour的对象不能通过new来创建
unity·c#·游戏引擎
爱吃小胖橘7 小时前
Unity-动画目标匹配
3d·unity·c#·游戏引擎
SmalBox7 小时前
【光照】[PBR][漫反射]实现方法对比
unity·渲染
PaoloBanchero10 小时前
Unity 虚拟仿真实验中设计模式的使用 ——命令模式(Command Pattern)
unity·设计模式·命令模式
HELLOMILI11 小时前
[UnrealEngine] 虚幻引擎UE5下载及安装(UE4、UE5)
游戏·ue5·游戏引擎·ue4·虚幻·软件需求
PaoloBanchero14 小时前
Unity 虚拟仿真实验中设计模式的使用 ——策略模式(Strategy Pattern)
unity·设计模式·策略模式
PaoloBanchero14 小时前
Unity 虚拟仿真实验中设计模式的使用 —— 观察者模式(Observer Pattern)
观察者模式·unity·设计模式
软件黑马王子16 小时前
2025Unity超详细《坦克大战3D》项目实战案例(上篇)——UI搭建并使用和数据持久化(附资源和源代码)
游戏·ui·unity·c#
爱吃小胖橘1 天前
Unity-动画子状态机
3d·unity·c#·游戏引擎