PyOpenGL对象不断绕原点旋转

时间:2018-10-23 14:44:58

标签: python opengl pyopengl

因此,我只是在测试以查看引擎中的工作原理,并尝试使用以下内容来旋转对象。

rot_y = Matrix44.from_y_rotation(glfw.get_time() * 0.5)

但是...它绕原点旋转而不是它的位置。

主要代码: http://hatebin.com/rtuqgeqptw

projection = pyrr.matrix44.create_perspective_projection_matrix(60.0, w_width/w_height, 0.1, 100.0)
sphere_model = matrix44.create_from_translation(Vector3([-4.0,0.0,-3.0]))
monkey_model = matrix44.create_from_translation(Vector3([0.0,0.0,-3.0]))

glUseProgram(shader)
model_loc = glGetUniformLocation(shader, "model")
view_loc = glGetUniformLocation(shader, "view")
proj_loc = glGetUniformLocation(shader, "proj")

glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)

while not glfw.window_should_close(window):
    glfw.poll_events()
    do_movement()

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    view = cam.get_view_matrix()
    glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)

    rot_y = Matrix44.from_y_rotation(glfw.get_time() * 0.5)

    glBindVertexArray(sphere_vao)
    glBindTexture(GL_TEXTURE_2D, sphere_tex)
    glUniformMatrix4fv(model_loc, 1, GL_FALSE, rot_y *sphere_model)
    glDrawArrays(GL_TRIANGLES, 0, len(sphere_obj.vertex_index))
    glBindVertexArray(0)

    glBindVertexArray(monkey_vao)
    glBindTexture(GL_TEXTURE_2D, monkey_tex)
    glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_model)
    glDrawArrays(GL_TRIANGLES, 0, len(monkey_obj.vertex_index))
    glBindVertexArray(0)

    glfw.swap_buffers(window)

glfw.terminate()

我不确定问题是什么,为什么它不会围绕自己的观点旋转。

1 个答案:

答案 0 :(得分:1)

如果希望模型围绕网格的原点旋转,则必须在模型矩阵之前应用旋转矩阵。首先旋转模型,然后平移它。 进一步注意,AnnotationParser的返回类型为numpy.array。这意味着您必须先制作一个Matrix44,然后才能将矩阵相乘。

交换平移和旋转矩阵以解决您的问题:

sphere_model = matrix44.create_from_translation(Vector3([-4.0,0.0,-3.0]))

rot_y = Matrix44.from_y_rotation(glfw.get_time() * 0.5)

# roation before tranasltion
model_mat = Matrix44(sphere_model) * rot_y
glUniformMatrix4fv(model_loc, 1, GL_FALSE, model_mat) 

请注意,必须从左到右读取矩阵乘法。另请参见matrix44.create_from_translation

translate * rotate

GLSL Programming/Vector and Matrix Operations

rotate * translate