在Unity中经常用到本地坐标(相对坐标)与世界坐标的转换,比如在开发某些UI组件时,本文整理了相关转换接口
测试层级如下图:
测试代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class JCTest_Trans : MonoBehaviour
{
public Transform mTestPoint;
void Start()
{
//本地坐标(相对于Point_Parent2)
Debug.Log(mTestPoint.localPosition);
var Point_Parent2 = mTestPoint.parent;
Debug.LogFormat("本地坐标(相对于Point_Parent2表式方法1):{0}", Point_Parent2.worldToLocalMatrix.MultiplyPoint(mTestPoint.position));
Debug.LogFormat("本地坐标(相对于Point_Parent2表式方法2):{0}", Point_Parent2.InverseTransformPoint(mTestPoint.position));
//本地坐标(在其他节点下的本地坐标)
var Point_Parent1 = mTestPoint.parent.parent;
Debug.LogFormat("本地坐标(相对于Point_Parent1表式方法1):{0}", Point_Parent1.worldToLocalMatrix.MultiplyPoint(mTestPoint.position));
Debug.LogFormat("本地坐标(相对于Point_Parent1表式方法2):{0}", Point_Parent1.InverseTransformPoint(mTestPoint.position));
//世界坐标
Debug.Log(mTestPoint.position);
//世界坐标(其他表示方法)
Debug.LogFormat("世界坐标(表式方法1):{0}", mTestPoint.parent.localToWorldMatrix.MultiplyPoint(mTestPoint.localPosition));
Debug.LogFormat("世界坐标(表式方法2):{0}", mTestPoint.parent.TransformPoint(mTestPoint.localPosition));
}
}
打印测试结果:

文章评论