Search code examples
c++openglglm-math

Why is the camera view matrix not changing the position of the point


glm::vec3 Position(0, 0, 500);
glm::vec3 Front(0, 0, 1);
glm::vec3 Up(0, 1, 0);

glm::vec3 vPosition = glm::vec3(Position.x, Position.y, Position.z);
glm::vec3 vFront = glm::vec3(Front.x, Front.y, Front.z);
glm::vec3 vUp = glm::vec3(Up.x, Up.y, Up.z);
glm::mat4 view1 = glm::lookAt(vPosition, vPosition + vFront, vUp);


glm::mat4 projection1 = glm::perspective(glm::radians(45.0f), (float)1920 / (float)1080, 0.1f, 1000.0f);

   glm::mat4 VPMatrix = projection1 * view1;    

float testZ = 0.0f;
glm::vec3 modelVertices(-50.0f, 50.0f, testZ);
glm::vec4 finalPositionMin = VPMatrix * glm::vec4(modelVertices, 1.0);
Print() << finalPositionMin.x;

In the code if i change the FOV value of perspective than that affects the object drawn on screen for smaller values object size increases on the screen.

  1. At FOV value of 45 the finalPositionMin.x is -50
  2. At FOV value of 25 the finalPositionMin.x is -126

but if i move the camera closer to the object than that should also affect the object and more closer we come to the object the finalPositionMin.x should be affected.

Why changing value the Z positon of camera is not affecting the finalPositionMin.x of the object ?


Solution

  • To get a Cartesian coordinate, you need to divide the x, y, and z components by the w component. You have to print finalPositionMin.x/finalPositionMin.w.

    Likely you confuse "window" coordinates and "world" coordinates. In your example, finalPositionMin is not in world space, it is in clip space. To get a world space coordinate you need to multiply modelVertices by the model matrix, but nothing else. Note, the view matrix (view1) transforms from world space to view space. The projection matrix (projection1 transforms from view space to clip space. With perspective divide you can transforms from clip space to a normalized device coordinate.
    To get window coordinates ("pixel" coordinates) you have to "project" the NDC onto the viewport (width, height is the size of the viewport):

    x = width * (ndc.x+1)/2
    y = height * (1-ndc.y)/2