模型视图投影 - 如何在世界中移动对象

Model View Projection - How to move objects in a world

我有一个 3D 世界,里面有一个立方体。我知道立方体的顶点定义为关于立方体 "centre of mass".

的坐标

我想把立方体放在远离我的位置,在右边和上面,所以我想把立方体放在 (1,1,1)。我目前没有任何 'camera' 代码,所以假设我的观看位置是 (0,0,0).

我需要翻译什么才能将立方体移动到新位置?

我对视图和模型矩阵感到困惑。我以为 View 是相机 view/position 而 Model 是顶点在 3D 世界中的位置。

我下面的代码在 x 和 y 位置上的工作方式与我预期的一样,但 z 进入屏幕(更远)时为负,屏幕正向移动 towards/out。我希望物体离视点越远 z 为正。

我做错了什么?

  glm::mat4 Projection = glm::perspective( 45.0f, g_AspectRatio, 0.1f, 100.0f );

  glm::mat4 View = glm::mat4(1.0);

  glm::mat4 Model = glm::mat4(1.0);

  // Move the object within the 3D space
  Model = glm::translate( Model, glm::vec3( m_X, m_Y, m_Z ) );

  glm::mat4 MVP;
  MVP = Projection * View * Model;

MVP 传入transform 制服。

我的着色器:

char *vs3DShader  = 

"#version 140\n"

"#extension GL_ARB_explicit_attrib_location : enable\n"

"layout (location = 0) in vec3 Position;"
"layout (location = 1) in vec4 color;"
"layout (location = 2) in vec3 normal;"

"out vec4 frag_color;"

"uniform mat4 transform;"

"void main()"
"{"
"  gl_Position = transform * vec4( Position.x, Position.y, Position.z, 1.0 );"

"  // Pass vertex color to fragment shader.. \n"
"  frag_color = color;"
"}"

;

My code below works as I expect for x and y positions but z is negative going into the screen (further away) and positive moving towards/out of the screen. I would like z to be positive the further away an object is from the viewpoint.

您可以通过设置一个视图矩阵来实现这一点,它反映了 Z-Axis:

glm::mat4 View = glm::scale(glm::mat4(1.0), glm::vec3(1.0f, 1.0f, -1.0f));


视图矩阵从世界 space 转换为视图 space。您的视图矩阵是单位矩阵:

glm::mat4 View = glm::mat4(1.0);

这意味着世界 space 等于视野 space。请注意,通常视图矩阵由 glm::lookAt.

设置

Z-Axis 是 X-Axis 和 Y-Axis 的叉积。这意味着,如果 X-axis 指向左侧,而 Y-axis 指向上方,在 right handed system 中,则 Z-axis 指向视口外。
参见 Understanding OpenGL’s Matrices


我上面描述的坐标通常是 right handed system 中的视图坐标,因为 glm::glm::perspective 设置了一个右手投影矩阵,它将这个坐标转换为裁剪空间,这样 z-axis被倒置成为深度。