简体   繁体   中英

How to position an object in model / view / world space?

I have a cube which is defined with the centre at 0,0,0 and the edges reaching out to -1/+1 (ie the cube has width, height, depth of 2).

I then setup the following matrices:

glm::mat4 modelMat4;
modelMat4 = glm::translate(modelMat4, 0.0f, 0.0f, 200.f);
modelMat4 = glm::scale(modelMat4, 200.0f, 200.0f, 200.0f);

glm::mat4 viewMat4;
viewMat4 = glm::lookAt(glm::vec3(0.0f, 0.0f, zNear),
            glm::vec3(0.0f, 0.0f, zFar),
            glm::vec3(0.0f, 1.0f, 0.0f));

// initialWidth = window width
// initialHeight = window height
// zNear = 1.0f
// zFar = 1000.0f
glm::mat4 projectionMat4;
projectionMat4 = glm::frustum(-initialWidth / 2.0f, initialWidth / 2.0f, -initialHeight / 2.0f, initialHeight / 2.0f, zNear, zFar);

But the middle of my object appears at the near z-plane (ie I can only see the back half of my cube, from the inside).

If I adjust the model transform to be:

glm::translate(modelMat4, 0.0f, 0.0f, 204.f);

Then I can see the front side of my cube as well.

If I change the model transform to be:

glm::translate(modelMat4, 0.0f, 0.0f, 250.f);

Then the cube only rasterises at approx 2x2x2 pixels.

What am I misunderstanding about model, view projection matrices? I was expecting the transform to be linear, but the z-plane disappears between 200 and 250. Even though the planes are defined between 1.0f and 1000.0f.

Edit: My shader code is below:

#version 100

layout(location = 0) in vec3 v_Position;
layout(location = 1) in vec4 v_Colour;

layout(location = 2) uniform mat4 v_ModelMatrix;
layout(location = 3) uniform mat4 v_ViewMatrix;
layout(location = 4) uniform mat4 v_ProjectionMatrix;

out vec4 f_inColour;

void main()
{
    gl_Position = v_ProjectionMatrix * v_ViewMatrix * v_ModelMatrix * vec4(v_Position, 1.0);
    f_inColour = v_Colour;
}

You didn't show how you are multiplying your matrices, but for what you describe, its seems that it could be doing wrong. Be sure to do in this order:

MVP = projectionMat4 * viewMat4 * modelMat4;

UPDATED

Looking more carefully into your code, it is seeming that you are lacking a multiplication to concanate your transformations:

modelMat4 = glm::translate(modelMat4, 0.0f, 0.0f, 200.f);
modelMat4 *= glm::scale(modelMat4, 200.0f, 200.0f, 200.0f); // <-- here

so, modelMat4 will be the results of a scale and then a translation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM