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

相关推荐
nnsix1 小时前
Unity的dllType Native和Managed的区别
unity·游戏引擎
编码旅者3 小时前
《Virt A Mate(VAM)》免安装豪华版v1.22中文汉化整合
游戏引擎·图形渲染·vr·动画
Clank的游戏栈3 小时前
AI游戏开发全自动编程课程体系(Cursor版,支持Unity/Cocos, Laya后续支持)
人工智能·unity·游戏引擎
鹿野素材屋4 小时前
技术闲聊:为什么网游会在固定时间点,刷出固定的道具?
前端·网络·unity
发际线危机121385 小时前
Unity发布apk部分真机虚线采样变成实线问题
unity·游戏引擎
FVV11235 小时前
电脑录屏工具Bandicam 无时长限制,支持4K画质
eclipse·游戏引擎·ar·动画·ogre
猫不吃咸鱼8 小时前
Unity中攻击检测敌人的多种方法
游戏·unity·c#·游戏引擎
又来0779 小时前
Unity 无人机物理模拟开发日志:从零打造穿越机手感
unity·游戏引擎·无人机
CreasyChan10 小时前
Unity UniRx Observable 类详解及使用
游戏·unity·c#·游戏引擎
老朱佩琪!13 小时前
Unity策略模式
unity·设计模式·策略模式