Unity的UGUI的坐标

一、先记住 4 种坐标(UGUI 必懂)

  1. 屏幕坐标 Screen 鼠标坐标、Input 输出的都是这个,左下角 (0,0),右上角 (Screen.width, Screen.height)
  2. 世界坐标 World transform.position,3D 通用坐标
  3. 本地坐标 Local transform.localPosition,相对于父节点的坐标
  4. UI 锚点坐标 Anchored rectTransform.anchoredPosition,UGUI 专用,相对于锚点的坐标

二、最常用坐标转换 API(直接背)

1. UI 自身 本地坐标 → 屏幕坐标

cs 复制代码
Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(
    Camera.main, 
    rectTransform.TransformPoint(localPos)
);

2. UI 锚点坐标 → 屏幕坐标

cs 复制代码
Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(
    uiCamera, 
    rectTransform.position
);

3. 屏幕坐标 → UI 锚点坐标(最常用!拖拽、跟随鼠标)

cs 复制代码
RectTransformUtility.ScreenPointToLocalPointInRectangle(
    父节点RT, 
    screenPos, 
    uiCamera, 
    out Vector2 anchoredPos
);

4. 屏幕坐标 → UI 世界坐标

cs 复制代码
RectTransformUtility.ScreenPointToWorldPointInRectangle(
    父节点RT, 
    screenPos, 
    uiCamera, 
    out Vector3 worldPos
);

5. 世界坐标 → 屏幕坐标

cs 复制代码
Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(camera, worldPos);

6. UI 本地坐标 ↔ 世界坐标

cs 复制代码
// 本地 → 世界
Vector3 world = rectTransform.TransformPoint(localPos);

// 世界 → 本地
Vector3 local = rectTransform.InverseTransformPoint(worldPos);

7. 任意 UI 坐标 → 另一个 UI 的本地坐标(跨父节点对齐神器)

cs 复制代码
// A 坐标 → 世界 → B 本地
Vector3 world = targetRT.TransformPoint(localPosA);
Vector3 localInB = myRT.InverseTransformPoint(world);

8. 获取 UI 四个角的屏幕坐标

cs 复制代码
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);

// 然后转屏幕
Vector2 screenLB = RectTransformUtility.WorldToScreenPoint(uiCamera, corners[0]);

三、Canvas 渲染模式区别(超级关键)

  • Screen Space - Overlay 相机传 null
  • Screen Space - Camera 传 Canvas.worldCamera
  • World Space 传 主相机

四、最常用 4 句背下来就够(90% 场景)

  1. 屏幕 → UI 锚点 ScreenPointToLocalPointInRectangle
  2. UI → 屏幕 WorldToScreenPoint
  3. 跨父节点 UI 对齐 TransformPoint + InverseTransformPoint
  4. 取 UI 四角 GetWorldCorners
相关推荐
警醒与鞭策9 小时前
Codex桌面版与Claude桌面版使用设置
android·unity·ai·性能优化
xcLeigh10 小时前
Unity基础:Destroy与DestroyImmediate——正确销毁游戏物体的方式
游戏·unity·游戏引擎·教程
lllhhh_远方15 小时前
unity中URP场景阴影锯齿严重解决方案
unity·游戏引擎
淡海水19 小时前
07-06-源码-.NET Core GC的极致优化技术
unity·架构·c#·.netcore·gc·1024程序员节
野区捕龙为宠19 小时前
Unity 中使用 UnityWebRequest 加载 StreamingAssets 文件夹中的图片
unity·游戏引擎
淡海水1 天前
07-02-源码-.NET Core GC分配路径
算法·unity·c#·.netcore·gc·1024程序员节
FFFFujige1 天前
【Unity】基于Dots + Luban的Buff模块
unity·游戏引擎
紫龙大侠1 天前
Unity许可证文件(激活成功后)默认保存位置
unity
Msir_Modern2 天前
Noita 元胞沙盒笔记
算法·unity·c#·游戏引擎·元胞自动机
天天进步20152 天前
Unity 2020.3 反复提示安全模式:一次 CS0009 与 DLL 文件占用的排查记录
unity·1024程序员节