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 天前
C# 语言进阶(十四)Unity UI界面开发 + 网络消息联动
服务器·开发语言·网络·ui·unity·c#·游戏引擎
野区捕龙为宠1 天前
Unity 持久化数据
unity·游戏引擎·lucene
郝学胜-神的一滴1 天前
[简化版 GAMES 101] 计算机图形学 17:纹理技术从基础原理到多场景实战应用
c++·unity·游戏引擎·图形渲染·three.js·opengl·unreal
_ZHOURUI_H_2 天前
MyFramework: 同样是 Unity 游戏开发框架,和 HTFramework 的设计取向有什么不同?(下)
unity·游戏引擎·游戏开发·游戏ui·手游开发
丁小未3 天前
基于MVVM框架的XUUI 扩展的UI管理系统教程
unity·mvvm·ui框架·xuui·ui管理器
丁小未4 天前
基于MVVM框架的XUUI HelloWorld 新手教程
unity·性能优化·c#·游戏引擎
丁小未4 天前
基于MVVM框架的XUUI MoreComplex案例
unity·c#
EQ-雪梨蛋花汤4 天前
【Unity笔记】VR 一体机画面锯齿、模型边缘闪烁、接缝抖动排查:MSAA、Mipmap、Render Scale、Z-Fighting 全流程记录
笔记·unity·vr
YigAin4 天前
Unity Spine 资源出现白边的解决办法
unity·游戏引擎·spine
郝学胜-神的一滴5 天前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal