如何在 PyOpenGL 中旋转 2D 线? [英] How to rotate a 2D line in PyOpenGL?
问题描述
我写了一个代码来画一条线.这是函数:
I've written a 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()
现在我正在尝试旋转线条.我正在尝试遵循 this 文档,但无法理解.根据文档,旋转函数定义如下:
Now I'm trying to rotate the line. I'm trying to follow this documentation but can't understand. According to the documentation the rotating function is defined as follows:
def glRotate( angle , x , y , z ):
我没有 z 轴.所以我保持 z=0
.我在这里错过了什么?
I've no z-axis. So I'm keeping z=0
. What i'm I missing here?
推荐答案
注意,不推荐使用 glBegin
/glEnd
序列和固定函数管道矩阵堆栈进行绘制几十年来.阅读Fixed Function Pipeline 并查看顶点规范 和 着色器 用于最先进的渲染方式:
Note, that drawing by glBegin
/glEnd
sequences nad the fixed function pipeline matrix stack, is deprecated since decades.
Read about Fixed Function Pipeline and see Vertex Specification and Shader for a state of the art way of rendering:
传递给 glRotate
是旋转轴.由于几何图形是在 xy 平面中绘制的,因此旋转轴必须是 z 轴 (0,0,1):
The x
, y
and z
parameter which are passed to glRotate
are the axis of rotation. Since geometry is drawn in the xy-plane, the axis of rotation has to be the z-axis (0,0,1):
glRotatef(10, 0, 0, 1)
要围绕枢轴旋转,您必须定义一个模型矩阵,该矩阵由倒置的枢轴位移,然后旋转并最终变换回枢轴 (glTranslate
):
To rotate around a pivot you have to define a model matrix, which displaces by the inverted pivot, then rotates and final transforms back by to the pivot (glTranslate
):
glTranslatef(pivot_x, pivot_y, 0)
glRotatef(10, 0, 0, 1)
glTranslatef(-pivot_x, -pivot_y, 0)
另外请注意,glBegin
/glEnd
序列.在 glBegin
/glEnd
仅允许设置顶点属性的序列操作,例如 glVertex
或 glColor
.你必须在 glBegin
之前设置矩阵:
Further note that operations like glRotate
are not allowed within a glBegin
/glEnd
sequence. In glBegin
/glEnd
sequence only operations are allowed which set the vertex attributes like glVertex
or glColor
. You have to set the matrix before glBegin
:
例如
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
:
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()
这篇关于如何在 PyOpenGL 中旋转 2D 线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!