从Unity3D到DirectX的投影矩阵

时间:2013-08-20 12:16:27

标签: graphics directx unity3d projection-matrix

我发现this question要在OpenGL和DirectX之间执行转换,但是当从Unity3D执行相同的操作时它似乎不起作用。

我希望这里有人知道OpenGL投影矩阵和Unity3D投影矩阵(以及视图矩阵!)之间的差异。

我也试过使用this article,但它也没有用。

在Unity3D中,我正在调用我自己的原生C ++插件:

SetView(MatrixToArray(Camera.current.worldToCameraMatrix));
SetProjection(MatrixToArray(Matrix4x4.identity));
SetWorld(MatrixToArray(Camera.current.projectionMatrix));

private static float[] MatrixToArray(Matrix4x4 _matrix)
{
    float[] result = new float[16];

    for (int _row = 0; _row < 4; _row++)
    {
        for (int _col = 0; _col < 4; _col++)
        {
            result[_col + _row * 4] = _matrix[_row, _col];
        }
    }

    return result;
}

在我的C ++插件中,我尝试通过the article转换这些矩阵:

extern "C" void EXPORT_API SetProjection(float a[])
{
    g_Proj._11 = a[0];
    g_Proj._21 = a[1];
    g_Proj._31 = -a[2];
    g_Proj._41 = a[3];
    g_Proj._12 = a[4];
    g_Proj._22 = a[5];
    g_Proj._32 = -a[6];
    g_Proj._42 = a[7];
    g_Proj._13 = a[8];
    g_Proj._23 = a[9];
    g_Proj._33 = -a[10];
    g_Proj._43 = a[11];
    g_Proj._14 = a[12];
    g_Proj._24 = a[13];
    g_Proj._34 = -a[14];
    g_Proj._44 = a[15];
}

extern "C" void EXPORT_API SetView(float a[])
{
    g_View._11 = a[0];
    g_View._21 = a[1];
    g_View._31 = -a[2];
    g_View._41 = a[3];
    g_View._12 = a[4];
    g_View._22 = a[5];
    g_View._32 = -a[6];
    g_View._42 = a[7];
    g_View._13 = -a[8];
    g_View._23 = -a[9];
    g_View._33 = a[10];
    g_View._43 = -a[11];
    g_View._14 = a[12];
    g_View._24 = a[13];
    g_View._34 = a[14];
    g_View._44 = a[15];
}

我知道绘制的东西,因为使用视图和投影矩阵的单位矩阵确实为顶点提供了一个三角形:{0,0,0},{0,1,0},{1,0,0} 。移动相机时我也会看到各种剪切效果。

编辑 - 更多信息:
Unity3D Documentation告诉我们它使用OpenGL表示法。

编辑 - 示例项目:
如果有人想试用我的代码,我已经创建了test project并将其上传到统一论坛。

1 个答案:

答案 0 :(得分:0)

article似乎工作正常,但似乎在我所有的冲动和尝试中,我将投影矩阵设置在世界矩阵中。

SetProjection(MatrixToArray(Matrix4x4.identity));
SetWorld(MatrixToArray(Camera.current.projectionMatrix));

应该是

SetWorld(MatrixToArray(Matrix4x4.identity));
SetProjection(MatrixToArray(Camera.current.projectionMatrix));

我在关于test project的统一论坛上提供了更多信息。