Skip to main content
 首页 » 编程设计

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

2025年02月15日9bonelee

我想弄清楚如何在不同的轴上旋转两个 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()     

请您参考如下方法:

OpenGL 操作如 glRotatef操纵 OpenGL 的最顶层元素 matrix stack .使用 glPushMatrix和 glPopMatrix将矩阵插入矩阵堆栈并从矩阵堆栈中弹出矩阵。 glMatrixMode为矩阵运算指定当前矩阵。
(参见 Legacy OpenGL)
定义网格位置和方向的矩阵是模型 View 矩阵。
(参见 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