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
相关推荐
zdr尽职尽责17 小时前
Unity 3C 动画系统:从「蜘蛛网」到可维护的动画架构
unity·架构·游戏引擎
国家一级摸鱼选手21 小时前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
暴走约伯3 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
寂寞的船4 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
寂寞的船5 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
探求虚无6 天前
用 AI 在 Unity 里做一款 RTS:最难的不是生成代码,而是证明它真的能玩
人工智能·unity·游戏引擎
17岁的勇气7 天前
Unity Shader unity文档学习笔记(二十二):shader变体
笔记·学习·unity
寂寞的船8 天前
【Unity知识速递】第10期 Unity GC 零分配实战:从 UnityEngine.Pool 到手动 GC 控制的全链路优化
jvm·unity·c#·游戏引擎·lucene
寂寞的船10 天前
【Unity知识速递】第8期 IL2CPP 托管堆内存碎片与原生堆交互机制深度解析
unity·游戏引擎·交互
寂寞的船11 天前
【Unity知识速递】第5期 Unity 6.2 深度解析:AI Assistant 登场,World Space UI 与 Sentis 全面升级
人工智能·ui·unity