【发布时间】:2019-12-03 10:28:48
【问题描述】:
我正在练习 OpenGL 和转换,但遇到了问题。我有四个立方体一起平移形成汽车的骨架。我希望能够在汽车不自行拆卸的情况下驾驶和转动汽车。基本上,我希望后备箱和汽车的前部围绕车身而不是原点 (0,0,0) 旋转。我已经阅读了要完成此操作,我必须遵循以下步骤:
从单位矩阵开始
按对象的中心平移矩阵
将矩阵旋转所需的量
按对象中心平移矩阵
使用生成的矩阵变换您想要旋转的对象
并已将其实现到我的代码中,但它没有按我预期的那样工作。请告诉我我做错了什么以及实现这一点的正确方法。我在下面粘贴了我的代码,并对其进行了修剪,所以这里只有重要的部分。
结果:
float xMove = 0.0f; //xMove and zMove keeps track of the center of the main body while driving
float zMove = 0.0f;
float carRotate = 0.0f; //degrees of rotation incremented by pressing E
int main()
{
/*some code to initialize the program...*/
while (!glfwWindowShouldClose(window))
{
/*Draw main car body*/
mat4 carMatrix = translate(mat4(1.0f), vec3(0.0f + xMove + x, 0.2f, 0.0f + zMove + z))
* rotate(mat4(1.0f), radians(carRotate), vec3(0.0f, 1.0f, 0.0f))
* scale(mat4(1.0f), vec3(0.5f, 0.4f, 1.0f))
* translate(mat4(1.0f), vec3(0.0f, -0.2f,0.0f));
shaderProgram.setMat4("model", carMatrix);
glDrawArrays(GL_TRIANGLES, 0, 36);
//Bonnet
carMatrix = translate(mat4(1.0f), vec3(0.0f + xMove + x, 0.1f, 0.65f + zMove + z))
* rotate(mat4(1.0f), radians(carRotate), vec3(0.0f, 1.0f, 0.0f))
* scale(mat4(1.0f), vec3(0.3f, 0.2f, 0.3f))
* translate(mat4(1.0f), vec3(xMove, 0.0f, -zMove));
shaderProgram.setMat4("model", carMatrix);
glDrawArrays(GL_TRIANGLES, 0, 36);
//Trunk
carMatrix = translate(mat4(1.0f), vec3(0.0f + xMove + x, 0.1f, -0.65f + zMove + z))
* rotate(mat4(1.0f), radians(carRotate), vec3(0.0f, 1.0f, 0.0f))
* scale(mat4(1.0f), vec3(0.3f, 0.2f, 0.3f))
* translate(mat4(1.0f), vec3(0.0f, 0.0f, 0.0f));
shaderProgram.setMat4("model", carMatrix);
glDrawArrays(GL_TRIANGLES, 0, 36);
//Roof
carMatrix = translate(mat4(1.0f), vec3(0.0f + xMove + x, 0.45f, 0.0f + zMove + z))
* rotate(mat4(1.0f), radians(carRotate), vec3(0.0f, 1.0f, 0.0f))
* scale(mat4(1.0f), vec3(0.3f, 0.1f, 0.6f))
* translate(mat4(1.0f), vec3(0.0f, 0.0f, 0.0f));
shaderProgram.setMat4("model", carMatrix);
glDrawArrays(GL_TRIANGLES, 0, 36);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
zMove++;
}
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
{
carRotate++;
}
}
}
【问题讨论】:
标签: c++ opengl glsl transformation glm-math