unity, 相机空间 与 相机gameObject的局部空间

在unity里 相机空间 与 相机gameObject的局部空间 不重合。

Camera.worldToCameraMatrix的文档中有这样一句话:

Note that camera space matches OpenGL convention: camera's forward is the negative Z axis. This is different from Unity's convention, where forward is the positive Z axis.

 

意思是说unity中相机gameObject的蓝轴是相机空间的-Z。

为了确认,做了如下实验:

如图,立方体的坐标是(0,0,0),相机的坐标是(0,0,-3),我们要计算并输出立方体在相机空间的坐标。

做法是为立方体添加如下脚本:

using UnityEngine;
using System.Collections;
public class printPosInCameraSpace : MonoBehaviour {
    public GameObject m_cameraRef;
    // Use this for initialization
    void Start () {
        Matrix4x4 worldToCameraMat = m_cameraRef.GetComponent<Camera>().worldToCameraMatrix;
        Vector3 thisPosInWorld = transform.position;
        Vector3 thisPosInCamera = worldToCameraMat.MultiplyPoint (thisPosInWorld);
        Debug.Log (thisPosInCamera);
    }
}

并在编辑器中将camera赋给m_cameraRef.

然后运行脚本,得到输出结果为:(0,0,-3)。

这说明相机gameObject的蓝轴确实是相机空间-Z轴。

进一步实验:

将脚本改为:

using UnityEngine;
using System.Collections;
public class printPosInCameraGameObjectLocalSpace : MonoBehaviour {
    public GameObject m_cameraRef;
    // Use this for initialization
    void Start () {
        Matrix4x4 worldToCameraMat = m_cameraRef.transform.worldToLocalMatrix;
        Vector3 thisPosInWorld = transform.position;
        Vector3 thisPosInCamera = worldToCameraMat.MultiplyPoint (thisPosInWorld);
        Debug.Log (thisPosInCamera);
    }
}

输出结果为:(0,0,3)。

 

--结论:

相机空间 和 相机gameObject的局部空间 是不重合的。图中这三个坐标轴表示的是 相机gameObject的局部空间。 而 相机空间 则Z轴方向与之相反。

Camera.worldToCameraMatrix是 世界空间to相机空间 矩阵。Camera.transform.worldToLocalMatrix是 世界空间to相机gameObject的局部空间 矩阵,两个矩阵是不一样的。

posted on   wantnon  阅读(1830)  评论(1编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示