【发布时间】:2019-02-13 11:53:39
【问题描述】:
我的目标是按箭头键移动对象。为此,在回调中,我从某个偏移量创建平移矩阵并将其乘以世界矩阵。但是它不起作用 - 立方体不会通过按键移动。我还注意到直接使用带有设置偏移量的 glTranslate() 效果很好,但看起来像拐杖。我的意思是,对于模型的任何转换,我都应该只使用转换矩阵。 我的代码中的问题在哪里?如何解决?为什么 glTranslate() 效果很好? 最小代码示例:
glm::mat4 mWorldMatrix;
glm::mat4 mViewMatrix;
glm::mat4 mProjMatrix;
void onKeyCallback(GLFWwindow*, int key, int scan, int action, int mods)
{
switch (key)
{
case GLFW_KEY_UP:
{
auto translationMatrix = glm::translate(glm::mat4{}, glm::vec3{ 0, 1, 0 });
mWorldMatrix = mWorldMatrix * translationMatrix;
break;
}
case GLFW_KEY_DOWN:
{
auto translationMatrix = glm::translate(glm::mat4{}, glm::vec3{ 0, -1, 0 });
mWorldMatrix = mWorldMatrix * translationMatrix;
break;
}
case GLFW_KEY_LEFT:
{
auto translationMatrix = glm::translate(glm::mat4{}, glm::vec3{ -1, 0, 0 });
mWorldMatrix = mWorldMatrix * translationMatrix;
break;
}
case GLFW_KEY_RIGHT:
{
auto translationMatrix = glm::translate(glm::mat4{}, glm::vec3{ 1, 0, 0 });
mWorldMatrix = mWorldMatrix * translationMatrix;
break;
}
}
}
int main()
{
glfwInit();
const int weight = 640;
const int height = 480;
auto mWindow = glfwCreateWindow(weight, height, "TesT", nullptr, nullptr);
glfwMakeContextCurrent(mWindow);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
mWorldMatrix = glm::mat4{ 1.0f };
mViewMatrix = glm::lookAt(glm::vec3{ 0, 0, -1 },
glm::vec3{ 0, 0, 0 },
glm::vec3{ 0, 1, 0 });
mProjMatrix = glm::perspective(glm::radians(45.0f),
static_cast<float>(weight) / height,
0.1f,
100.0f);
glfwSetKeyCallback(mWindow, onKeyCallback);
while (!glfwWindowShouldClose(mWindow)) {
glClearColor(0.5, 0.5, 0.5, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0,0, weight, height);
auto modelViewMatrix = mViewMatrix * mWorldMatrix;
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(static_cast<const float*>(glm::value_ptr(modelViewMatrix)));
glMatrixMode(GL_PROJECTION_MATRIX);
glLoadMatrixf(static_cast<const float*>(glm::value_ptr(mProjMatrix)));
Cube cube{ glm::vec3{0.5, 0.5, 0.5}, 1 }; //cube with center in {0.5} and side length 1
auto vertices = cube.soup(); //vector of vertex
glTranslatef(0 /* + offset.x*/, 0/* + offset.y*/, -5); //Setting offset here is work good
glBegin(GL_TRIANGLES);
for (const auto& vertex : vertices)
{
glColor3f(vertex.position.x, vertex.position.y, vertex.position.z);
glVertex3f(vertex.position.x, vertex.position.y, vertex.position.z);
}
glEnd();
glfwSwapBuffers(mWindow);
glfwWaitEvents();
}
glfwTerminate();
return 0;
}
【问题讨论】:
-
您是否错过了将矩阵应用于顶点位置的步骤?您每次都重新初始化顶点,但不要应用您的可变矩阵