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 - CameraCanvas.worldCamera
  • World Space主相机

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

  1. 屏幕 → UI 锚点 ScreenPointToLocalPointInRectangle
  2. UI → 屏幕 WorldToScreenPoint
  3. 跨父节点 UI 对齐 TransformPoint + InverseTransformPoint
  4. 取 UI 四角 GetWorldCorners
相关推荐
新的瑞拉公主1 天前
Unity游戏发布微信小游戏:从构建到提审
unity·webgl·微信小游戏·开放数据域
心前阳光3 天前
Unity发布PC软件图标不能改变
unity·游戏引擎
an86950013 天前
unity如何在visual studio中打断点debug
unity·游戏引擎·visual studio
xcLeigh3 天前
Unity基础:使用Transform控制物体移动——Translate与position详解
unity·游戏引擎
FairGuard手游加固3 天前
Unity小游戏加密:global-metadata.dat与AssetBundle保护
游戏·unity·游戏引擎
真鬼1233 天前
【Unity AI】Untiy链接cursor与MCP
unity·游戏引擎
WarPigs3 天前
Unity设置人物位置无效的原因
unity
程序员正茂3 天前
Unity3d行为树Behavior Designer Pro
unity·行为树
玖玥拾3 天前
Lua 基础语法(八) Unity Huatuo (HybridCLR)
开发语言·unity·游戏引擎·lua
平行云3 天前
国产GPU云渲染适配实战:驱动兼容、编码调优与多路并发
unity·ue5·webrtc·webgl·实时云渲染·云桌面·像素流送