Unity 获取局部坐标点在世界坐标系下的位置
要获取一个点在世界坐标下的位置,需要使用点所在的对象的世界变换矩阵。可以使用 Transform 组件的 TransformPoint 方法将点的局部坐标转换为世界坐标。
以下是获取一个点在世界坐标下的位置的示例代码:
using UnityEngine;
public class Example : MonoBehaviour
{
public Transform point; // 要获取位置的点所在的对象
private void Start()
{
// 获取点的局部坐标
Vector3 localPosition = point.localPosition;
// 获取点所在对象的世界变换矩阵
Matrix4x4 worldMatrix = point.localToWorldMatrix;
// 使用世界变换矩阵将点的局部坐标转换为世界坐标
Vector3 worldPosition = worldMatrix.MultiplyPoint3x4(localPosition);
Debug.Log('Point position in world coordinates: ' + worldPosition);
}
}
在上述代码中,我们首先使用 point.localPosition 获取点的局部坐标。然后,使用 point.localToWorldMatrix 获取点所在对象的世界变换矩阵。最后,使用 Matrix4x4.MultiplyPoint3x4 方法将点的局部坐标转换为世界坐标。最终的世界坐标存储在 worldPosition 变量中。
原文地址: https://www.cveoy.top/t/topic/hKUf 著作权归作者所有。请勿转载和采集!