ekremer
ekremer

Reputation: 311

Change camera position and direction in OpenGL?

I have a code (game) with a fixed camera in an ortho projection. It runs smoothly until I change the camera position from (0,0,1) to (0,0,-1).

In a nutshell, I have 2 textures:

{    //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      
}

the transformation matrices:

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
    );

the vertex shader:

#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 );
}

If I run this code, it properly displays both textures, does depth testing,...

However, if I change the camera position to (0, 0, -1) and textures' Z-coordinate to their inverse +5 and +7, and keep the same direction (0, 0, 0), no texture is displayed (rendered). Shouldn't it display the same as before the changes ?

Upvotes: 2

Views: 7726

Answers (1)

Rabbid76
Rabbid76

Reputation: 210878

The issue is related to the orthographic projection matrix, because it is not centered. When the z axis of the view is inverted, then the x axis is inverted, too. Note the Right-hand rule has to be still fulfilled and the x.axis is the cross product of the y-axis and z-axis.

When the geometry is at z-5and the view and projection matrix is as follows

 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);

then the object is projected to the viewport:

But if you switch the z position of the geometry and the view, then you get the following situation:

 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);

then the object is beside the viewport:

Shift the the orthographic projection along the X-axis, to solve your issue:

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

Upvotes: 3

Related Questions