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
相关推荐
WarPigs20 小时前
Unity对象不应该使用null传播的问题
unity
每日出拳老爷子2 天前
【VR】【Unity】抓走转放系列21|一天搭完门和抽屉工具槽:小场景按这个次序拼装
unity·vr·驱动·排错·snap zone
淡海水2 天前
02-02-原理篇-分代GC
算法·unity·c#·游戏引擎·.net·gc
小贺儿开发3 天前
Unity 文物新生 会讲故事的文物展墙
人工智能·科技·unity·ai·视频·互动·演示
淡海水3 天前
02-03-原理篇-大对象堆
unity·c#·游戏引擎·.net·gc
WarPigs4 天前
Unity在Create菜单添加创建自定义脚本模板选项
unity
淡海水4 天前
02-01-原理篇-Mark-Sweep与变种算法
算法·unity·c#·游戏引擎·.net·gc
babywang04 天前
Unity笔记--塔防游戏中的ECS架构:从原理到实战的全面解析
unity·ecs架构
babywang05 天前
Unity笔记--AssetBundle详解
unity·游戏引擎
淡海水5 天前
01-04-认知篇-Unity内存全景
unity·c#·游戏引擎·.net·gc