PyOpenGL 获取键盘输入

PyOpenGL Taking keyboard input

我正在尝试使用 PyOpenGL 在 Python 中制作一个光线投射器,我完成了一个黄色的小方块。主要是我需要键盘输入来移动我的方块,我做了一些东西但它不起作用。这是代码:

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import math

def drawPlayer():
    glColor3f(1,1,0)
    glPointSize(8)
    glBegin(GL_POINTS)
    glVertex2i(px,py)
    glEnd()

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    drawPlayer()
    glutSwapBuffers()

# Here is my keyboard input code
def buttons(key,x,y):
    if key == 'a':
        px -= 5
    if key == 'd':
        px += 5
    if key == 'w':
        py -= 5
    if key == 's':
        py += 5

def init():
    glClearColor(0.3,0.3,0.3,0)
    gluOrtho2D(0,1024,512,0)
    global px, py
    px = 300; py = 300

def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
    glutInitWindowSize(1024, 512)
    window = glutCreateWindow("Raycaster in python")
    init()
    glutDisplayFunc(display)
    glutKeyboardFunc(buttons)
    glutMainLoop()

if __name__ == "__main__":
    main()

为什么这段代码不起作用?

在全局命名空间中定义 pxpy

px = 300; py = 300

def drawPlayer():
    glColor3f(1,1,0)
    glPointSize(8)
    glBegin(GL_POINTS)
    glVertex2i(px,py)
    glEnd()

使用 global statement to change the variables in the global namespace within the button callback. Use the bytesprefix to compare the key to a letter (e.g. key == b'a'). Invoke glutPostRedisplay 将当前 window 标记为需要重新显示:

def buttons(key,x,y):
    global px, py
    if key == b'a':
        px -= 5
    if key == b'd':
        px += 5
    if key == b'w':
        py -= 5
    if key == b's':
        py += 5
    glutPostRedisplay()

完整示例

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import math

px = 300; py = 300

def drawPlayer():
    glColor3f(1,1,0)
    glPointSize(8)
    glBegin(GL_POINTS)
    glVertex2i(px,py)
    glEnd()

def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    drawPlayer()
    glutSwapBuffers()

# Here is my keyboard input code
def buttons(key,x,y):
    global px, py
    if key == b'a':
        px -= 5
    if key == b'd':
        px += 5
    if key == b'w':
        py -= 5
    if key == b's':
        py += 5
    glutPostRedisplay()

def init():
    glClearColor(0.3,0.3,0.3,0)
    gluOrtho2D(0,1024,512,0)    

def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
    glutInitWindowSize(1024, 512)
    window = glutCreateWindow("Raycaster in python")
    init()
    glutDisplayFunc(display)
    glutKeyboardFunc(buttons)
    glutMainLoop()

if __name__ == "__main__":
    main()