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

相关推荐
开发游戏的老王9 小时前
虚幻引擎入门教程:虚幻编辑器的基本操作
编辑器·游戏引擎·虚幻
AA陈超12 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-08 UI 部件数据表
c++·游戏·ue5·游戏引擎·虚幻
future_studio14 小时前
聊聊 Unity(小白专享、C# 小程序 之 播放器)
unity·小程序·c#
向宇it15 小时前
【unity实战】MapMagic 2实战例子
游戏·3d·unity·c#·游戏引擎
SlowFeather17 小时前
Unity TMP可控角度多色渐变文字
unity·游戏引擎
霜绛1 天前
Unity:UGUI笔记(一)——三大基础控件、组合控件
笔记·学习·unity·游戏引擎
小趴菜82271 天前
Android中加载unity aar包实现方案
android·unity·游戏引擎
今夕资源网2 天前
牛童三国单机游戏Unity源码 免费开源
游戏·unity·单机游戏·游戏源码·unity源码·unity游戏
future_studio2 天前
聊聊 Unity(小白专享、C# 小程序 之 图片播放器)
unity·小程序·c#
ellis19702 天前
toLua[七] Examples 06_LuaCoroutine2分析
unity