2017-09-14 80 views
2

我想弄清楚如何在不同的轴上旋转两个3D立方体。我可以创建两个立方体,并且可以在同一个方向上旋转这两个立方体,但是当我尝试在不同方向上旋转它们时,似乎只是将两个旋转混合在一起以形成两个立方体的新旋转轴。此外,我对Python和面向对象编程都很陌生。 谢谢如何使用类和pyopengl在不同的轴上旋转两个线框立方体

这是我的代码。

import pygame 
from pygame.locals import * 
from OpenGL.GL import * 
from OpenGL.GLU import * 
import time 


class cubeClass: 
    def __init__(self): 

     self.rotation = [0,0,0,0] 

     self.verticies =[ 
      (1, -1, -1), 
      (1, 1, -1), 
      (-1, 1, -1), 
      (-1, -1, -1), 
      (1, -1, 1), 
      (1, 1, 1), 
      (-1, -1, 1), 
      (-1, 1, 1) 
      ] 

     self.edges = (
      (0,1), 
      (0,3), 
      (0,4), 
      (2,1), 
      (2,3), 
      (2,7), 
      (6,3), 
      (6,4), 
      (6,7), 
      (5,1), 
      (5,4), 
      (5,7) 
      ) 

    def cube(self): 

     glBegin(GL_LINES) 
     for self.edge in self.edges: 
      for self.vertex in self.edge: 
       glVertex3fv(self.verticies[self.vertex]) 
     glEnd() 

     glRotatef(self.rotation[0],self.rotation[1], 
        self.rotation[2],self.rotation[3]) 
     print(self.rotation) 

def main(): 
    pygame.init() 
    display = (800,600) 
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL) 

    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0) 

    cube1 = cubeClass() 
    cube1.rotation= [1,1,0,0] 

    cube2 = cubeClass() 
    cube2.rotation = [1,0,1,0] 

    glTranslatef(0.0,0.0, -5) 

    while True: 
     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       pygame.quit() 
       quit() 

     glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) 

     cube1.cube() 
     cube2.cube() 

     pygame.display.flip() 

     pygame.time.wait(10) 
     #time.sleep(.04) 

main()  
+0

@ Rabbid76谢谢!这正是我寻找的glPushMatrix()和glPopMatrix()的信息和用法。 – Hats

+0

不客气。如果问题的答案完全解决了您的问题,那么您应该接受答案(答案左侧的复选标记)。 – Rabbid76

回答

1

glRotatef OpenGL的业务操作的OpenGL matrix stack的最顶端的元素。使用glPushMatrixglPopMatrix将矩阵推出并从矩阵堆栈弹出矩阵。 glMatrixMode指定矩阵运算的当前矩阵。
(请参阅Legacy OpenGL
定义网格位置和方向的矩阵是模型视图矩阵。
(请参阅Transform the modelMatrix

您必须为每个立方体单独设置旋转,并且必须逐步递增旋转角度。适应你的代码是这样的:

def cube(self): 

    glMatrixMode(GL_MODELVIEW) 
    glPushMatrix() 
    glRotatef(self.rotation[0],self.rotation[1], 
       self.rotation[2],self.rotation[3]) 

    glBegin(GL_LINES) 
    for self.edge in self.edges: 
     for self.vertex in self.edge: 
      glVertex3fv(self.verticies[self.vertex]) 
    glEnd() 

    print(self.rotation) 

    glPopMatrix() 
    self.rotation[0] = self.rotation[0] + 1 
相关问题