首页 > 解决方案 > 如何在 PyOpenGL 中旋转二维线?

问题描述

我写了一个代码来画一条线。这是功能:

def drawLines():
    r,g,b = 255,30,20
    #drawing visible axis
    glClear(GL_COLOR_BUFFER_BIT)
    glColor3ub(r,g,b)
    glBegin(GL_LINES)
    #glRotate(10,500,-500,0)
    glVertex2f(0,500)
    glVertex2f(0,-500)

    glEnd()
    glFlush()

现在我正在尝试旋转这条线。我正在尝试遵循文档,但无法理解。根据文档,旋转功能定义如下:

def glRotate( angle , x , y , z ):

我没有z轴。所以我保持z=0。我在这里想念什么?

标签: pythonopenglcoordinate-transformationpyopenglopengl-compat

解决方案


请注意,由glBegin/glEnd序列和固定函数管道矩阵堆栈绘制,几十年来已被弃用。阅读Fixed Function Pipeline并查看Vertex Specification and Shader了解最先进的渲染方式:


传递给的 和参数x是旋转轴。由于几何图形是在 xy 平面中绘制的,因此旋转轴必须是 z 轴 (0,0,1):yzglRotate

glRotatef(10, 0, 0, 1)

要围绕枢轴旋转,您必须定义一个模型矩阵,该矩阵由反转的枢轴置换,然后旋转并最终变换回枢轴(glTranslate):

glTranslatef(pivot_x, pivot_y, 0)
glRotatef(10, 0, 0, 1)
glTranslatef(-pivot_x, -pivot_y, 0)

进一步注意,在/序列glRotate中不允许进行类似的操作。在/序列中,仅允许设置顶点属性的操作,如或。您必须在之前设置矩阵:glBeginglEndglBeginglEndglVertexglColorglBegin

例如

def drawLines():
    pivot_x, pivot_y = 0, 250
    r,g,b = 255,30,20

    glTranslatef(pivot_x, pivot_y, 0)
    glRotatef(2, 0, 0, 1)
    glTranslatef(-pivot_x, -pivot_y, 0)

    glClear(GL_COLOR_BUFFER_BIT)
    glColor3ub(r,g,b)

    #drawing visible axis
    glBegin(GL_LINES)
    glVertex2f(0,500)
    glVertex2f(0,-500)
    glEnd()

    glFlush()

如果您只想旋转线条而不影响其他对象,那么您可以通过glPushMatrix/glPopMatrix保存和恢复 matirx 堆栈:

angle = 0

def drawLines():
    global angle 
    pivot_x, pivot_y = 0, 250
    r,g,b = 255,30,20

    glClear(GL_COLOR_BUFFER_BIT)

    glPushMatrix()

    glTranslatef(pivot_x, pivot_y, 0)
    glRotatef(angle, 0, 0, 1)
    angle += 2
    glTranslatef(-pivot_x, -pivot_y, 0)

    glColor3ub(r,g,b)

    #drawing visible axis
    glBegin(GL_LINES)
    glVertex2f(0,500)
    glVertex2f(0,-500)
    glEnd()

    glPopMatrix()

    glFlush()

推荐阅读