17

我正在渲染一个圆锥体,我想将它逆时针旋转 90 度,使尖端朝西!我正在使用 OpenGL 3+。

到目前为止,这是我在 Cone.cpp 中的代码:

//PROJECTION
    glm::mat4 Projection = glm::perspective(45.0f, 1.0f, 0.1f, 100.0f);

    //VIEW
    glm::mat4 View = glm::mat4(1.);
    View = glm::translate(View, glm::vec3(2.0f,4.0f, -25.0f));

    //MODEL
    glm::mat4 Model = glm::mat4(1.0);
    //Scale by factor 0.5
    Model = glm::scale(glm::mat4(1.0f),glm::vec3(0.5f));

    glm::mat4 MVP = Projection * View * Model;
    glUniformMatrix4fv(glGetUniformLocation(shaderprogram_spaceship, "MVP_matrix"), 1, GL_FALSE, glm::value_ptr(MVP));

    glClearColor(0.0, 0.0, 0.0, 1.0);

    glDrawArrays(GL_LINE_STRIP, start_cone, end_cone );

并未显示所有代码。

有人可以指导我完成轮换吗?我必须乘以视图矩阵吗?带有“glm 旋转”功能?

4

3 回答 3

47

您需要将模型矩阵相乘。因为那是模型位置、缩放和旋转应该在的地方(这就是为什么它被称为模型矩阵)。

您需要做的就是(见这里

Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)

请注意,要将度数转换为弧度,请使用 glm::radians(degrees)

这需要模型矩阵并在已经存在的所有操作之上应用旋转。其他函数 translate 和 scale 做同样的事情。这样就可以在一个矩阵中组合许多转换。

注意:早期版本接受以度为单位的角度。自0.9.6 起已弃用

Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
于 2012-02-08T10:09:51.347 回答
9

GLM 有很好的轮换示例:http: //glm.g-truc.net/code.html

glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.f);
glm::mat4 ViewTranslate = glm::translate(
    glm::mat4(1.0f),
    glm::vec3(0.0f, 0.0f, -Translate)
);
glm::mat4 ViewRotateX = glm::rotate(
    ViewTranslate,
    Rotate.y,
    glm::vec3(-1.0f, 0.0f, 0.0f)
);
glm::mat4 View = glm::rotate(
    ViewRotateX,
    Rotate.x,
    glm::vec3(0.0f, 1.0f, 0.0f)
);
glm::mat4 Model = glm::scale(
    glm::mat4(1.0f),
    glm::vec3(0.5f)
);
glm::mat4 MVP = Projection * View * Model;
glUniformMatrix4fv(LocationMVP, 1, GL_FALSE, glm::value_ptr(MVP));
于 2012-07-09T22:33:05.473 回答
6

我注意到,如果您没有正确指定角度,您也可能会出错,即使在使用时glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z))您仍然可能会遇到问题。我为此找到的解决方法是将类型指定为,glm::rotate(Model, (glm::mediump_float)90, glm::vec3(x, y, z))而不仅仅是说glm::rotate(Model, 90, glm::vec3(x, y, z))

或者只写第二个参数,以弧度为单位的角度(以前以度为单位),作为不需要强制转换的浮点数,例如:

glm::mat4 rotationMatrix = glm::rotate(glm::mat4(1.0f), 3.14f, glm::vec3(1.0));

如果您想继续使用度数,可以添加 glm::radians() 。并添加包括:

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
于 2016-08-02T17:56:32.530 回答