Python – How to rotate 2D lines in PyOpenGL?

How to rotate 2D lines in PyOpenGL?… here is a solution to the problem.

How to rotate 2D lines in PyOpenGL?

I wrote a piece of code to draw a line. Here is the function:

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

Now I’m trying to rotate the line. I’m trying to follow this doc but can’t understand it. According to the documentation, the rotation function is defined as follows:

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

I don’t have a z-axis. So I keep z=0. What am I missing here?

Solution

Note that drawing through glBegin/glEnd sequences and fixed-function pipeline matrix stacks has been deprecated for decades.
Learn about Fixed Function Pipeline and check it out Vertex Specification and Shader for state-of-the-art rendering:


passed to glRotate xThe y and z parameters are the axis of rotation. Because the geometry is drawn in the xy plane, the axis of rotation must be the z-axis (0,0,1):

glRotatef(10, 0, 0, 1)

To rotate around a pivot, you must define a model matrix that is displaced by an inverted pivot, then rotated and eventually converted back to the pivot ( glTranslate):

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

Note further that operations like glRotate Not allowed in glBegin/glEnd. Order. 在 >glBegin/glEnd Only sequence operations are allowed to set vertex properties, such as glVertex or glColor Before setting the matrix:

For example

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

If you just want to rotate the line without affecting other objects, then you can > by glPushMatrix/glPopMatrix saves and restores the matirx stack. :

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

Related Problems and Solutions