更改相机在OpenGL中的位置和方向?

时间:2019-03-08 16:08:12

标签: c++ opengl glm-math

我有一个带有固定摄像头的代码(游戏),该摄像头是正交投影。在我将相机位置从(0,0,1)更改为(0,0,-1)之前,它运行得很顺利。

简而言之,我有2种纹理:

{    //texture 1               
     960.0f,     0.0f,   -5.0f,    0.0f,   0.0f,      
     960.0f,  1080.0f,   -5.0f,    1.0f,   0.0f,      
    1920.0f,     0.0f,   -5.0f,    0.0f,   1.0f,    
    1920.0f,  1080.0f,   -5.0f,    1.0f,   1.0f      
}

{   // texture 2                        
    1290.0f,   390.0f,   -7.0f,    0.0f,   0.0f,    
    1290.0f,   690.0f,   -7.0f,    1.0f,   0.0f,    
    1590.0f,   390.0f,   -7.0f,    0.0f,   1.0f,    
    1590.0f,   690.0f,   -7.0f,    1.0f,   1.0f      
}

转换矩阵:

view = glm::lookAt
    (           
    glm::vec3(  0.0f,  0.0f,  1.0f  ),   
    glm::vec3(  0.0f,  0.0f,  0.0f  ),
    glm::vec3(  0.0f,  1.0f,  0.0f  )
    );

projection = glm::ortho
    (
    0.0f,   
    1920.0f,
    0.0f, 
    1080.0f,
    1.0f,   // zNear
    10.0f   // zFar
    );

顶点着色器:

#version 330 core

layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord;

out vec2 TexCoord;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4( aPos, 1.0 );

    TexCoord = vec2( aTexCoord.x, aTexCoord.y );
}

如果我运行此代码,它将正确显示两个纹理,进行深度测试,...

但是,如果我将相机位置更改为(0, 0, -1),并且将纹理的Z坐标更改为其倒数+5+7,并保持相同的方向(0, 0, 0),则不会显示(渲染)纹理。它不应该显示与更改之前相同的内容吗?

1 个答案:

答案 0 :(得分:2)

该问题与正交投影矩阵有关,因为它不居中。当视图的z轴反转时,x轴也反转。请注意,Right-hand rule仍必须满足,并且x.axis是y轴和z轴的叉积。

当几何图形位于z-5且视图和投影矩阵如下时

 view = glm::lookAt(
     glm::vec3(0.0f, 0.0f, 1.0f),
     glm::vec3(0.0f, 0.0f, 0.0f),
     glm::vec3(0.0f, 1.0f, 0.0f);
 projection = glm::ortho(0.0f, 1920.0f, 0.0f, 1080.0f, 1.0f, 10.0f);

然后将对象投影到视口:

但是,如果切换几何图形和视图的z位置,则会出现以下情况:

 view = glm::lookAt(
     glm::vec3(0.0f, 0.0f, -1.0f),
     glm::vec3(0.0f, 0.0f, 0.0f),
     glm::vec3(0.0f, 1.0f, 0.0f);

然后该对象在视口旁边:

沿着X轴移动正投影,以解决您的问题:

projection = glm::ortho(-1920.0f, 0.0f, 0.0f, 1080.0f, 1.0f, 10.0f);