如何使用 类 和 pyopengl 在不同轴上旋转两个线框立方体

How to rotate two wire frame cubes on different axis using classes and pyopengl

我想弄清楚如何在不同的轴上旋转两个 3D 立方体。我可以创建两个立方体,并且可以沿相同方向旋转两个立方体,但是当我尝试沿不同方向旋转它们时,它似乎只是混合了两个旋转以形成两个立方体的新旋转轴。我也是 Python 和面向对象编程的新手。 谢谢

这是我的代码。

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()    

glRotatef manipulate the top most element of the OpenGL matrix stack. Use glPushMatrix and glPopMatrix to push matrices on and pop matrices from the matrix stack. glMatrixMode这样的OpenGL操作为矩阵操作指定了当前矩阵。
(参见 Legacy OpenGL
定义网格位置和方向的矩阵是模型视图矩阵。
(参见

您必须为每个立方体单独设置旋转,并且必须逐渐增加旋转角度。像这样调整您的代码:

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