Unity LocalPosition 和 Position 的区别?还有其他的Position 没?

Unity 中的 LocalPositionPosition 是 Transform 组件中两个核心的位置属性,它们有以下关键区别:

1. Position(世界坐标)

  • 参考系:世界坐标系(World Space)

  • 描述:物体在游戏世界中的绝对位置

复制代码
/ 获取世界坐标
Vector3 worldPos = transform.position;

// 设置世界坐标
transform.position = new Vector3(10, 0, 5);

2. LocalPosition(局部坐标)

  • 参考系:父物体的局部坐标系(Local Space)

  • 描述:相对于父物体 Transform 的位置

复制代码
/ 获取局部坐标
Vector3 localPos = transform.localPosition;

// 设置局部坐标
transform.localPosition = new Vector3(0, 1, 0);

3. 关键区别

特性 Position LocalPosition
参考系 世界坐标系 父物体坐标系
父物体移动时 保持不变 跟随父物体变化
无父物体时 与 LocalPosition 相同 与 Position 相同
适用场景 全局定位、物理计算 层级结构、相对定位

4. 其他重要的 Position 相关属性

4.1 AnchoredPosition(UI 系统)

  • 仅用于RectTransform(UI 元素)

  • 参考系:相对于锚点的位置

复制代码
// UI 元素专用
RectTransform rt = GetComponent<RectTransform>();
rt.anchoredPosition = new Vector2(100, 50);

4.2 LocalPositionInAncestor

  • 在特定祖先坐标系中的局部位置

4.3 坐标系转换方法

复制代码
// 1. 世界坐标 → 局部坐标
Vector3 localPos = transform.parent.InverseTransformPoint(worldPos);

// 2. 局部坐标 → 世界坐标
Vector3 worldPos = transform.parent.TransformPoint(localPos);

// 3. 屏幕坐标 → 世界坐标(3D)
Vector3 screenPos = Camera.main.WorldToScreenPoint(worldPos);
Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);

// 4. UI 屏幕坐标 → UI 局部坐标
RectTransformUtility.ScreenPointToLocalPointInRectangle(
    parentRect, 
    screenPos, 
    canvasCamera, 
    out Vector2 localPos
);

5. 使用建议

  • 使用 Position:当需要精确的世界位置时(如生成物体、物理计算)

  • 使用 LocalPosition:当物体是层级结构的一部分时(如角色部件、UI 嵌套)

  • UI 系统 :优先使用 anchoredPositionoffsetMin/offsetMax

6. 转换关系公式

复制代码
世界坐标 = 父物体世界坐标 + (父物体旋转 × 局部坐标 × 父物体缩放)

7. 示例场景

复制代码
// 创建一个父子结构
GameObject parent = new GameObject("Parent");
GameObject child = new GameObject("Child");

child.transform.parent = parent.transform;

// 设置父物体位置
parent.transform.position = new Vector3(5, 0, 0);

// 设置子物体局部位置
child.transform.localPosition = new Vector3(0, 2, 0);

// 此时:
// child.transform.localPosition = (0, 2, 0)
// child.transform.position = (5, 2, 0) ← 世界坐标

总结

理解这些位置属性的关键在于明确参考坐标系Position 用于全局定位,LocalPosition 用于相对定位,而 anchoredPosition 则是 UI 系统的专用属性。根据具体需求选择合适的坐标系统能大大提高开发效率。

DEEP SEEK生成

相关推荐
在路上看风景7 小时前
31. Unity 异步加载的底层细节
unity
天人合一peng9 小时前
Unity中做表头时像work中整个调整宽窄
unity
小李也疯狂21 小时前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的21 小时前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y21 小时前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表
EQ-雪梨蛋花汤21 小时前
【Unity优化】Unity多场景加载优化与资源释放完整指南:解决Additive加载卡顿、预热、卸载与内存释放问题
unity·游戏引擎
我的offer在哪里21 小时前
用 Unity 从 0 做一个「可以玩的」游戏,需要哪些步骤和流程
游戏·unity·游戏引擎
泡泡茶壶ᐇ1 天前
Unity游戏开发入门指南:从零开始理解游戏引擎核心概念
unity·游戏引擎
YigAin1 天前
Unity中的Lock,到底在锁什么,什么时候该用?
unity
Var_al1 天前
抖小Unity WebGL分包命令行工具实践指南
unity·游戏引擎·webgl