I’m trying to make a raycaster in Python with PyOpenGL and i accomplished to make a little yellow square. Main thing is that i need keyboard input to move my square and i made something but it is not working. Here is the code:
JavaScript
x
48
48
1
from OpenGL.GL import *
2
from OpenGL.GLU import *
3
from OpenGL.GLUT import *
4
import sys
5
import math
6
7
def drawPlayer():
8
glColor3f(1,1,0)
9
glPointSize(8)
10
glBegin(GL_POINTS)
11
glVertex2i(px,py)
12
glEnd()
13
14
def display():
15
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
16
drawPlayer()
17
glutSwapBuffers()
18
19
# Here is my keyboard input code
20
def buttons(key,x,y):
21
if key == 'a':
22
px -= 5
23
if key == 'd':
24
px += 5
25
if key == 'w':
26
py -= 5
27
if key == 's':
28
py += 5
29
30
def init():
31
glClearColor(0.3,0.3,0.3,0)
32
gluOrtho2D(0,1024,512,0)
33
global px, py
34
px = 300; py = 300
35
36
def main():
37
glutInit(sys.argv)
38
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
39
glutInitWindowSize(1024, 512)
40
window = glutCreateWindow("Raycaster in python")
41
init()
42
glutDisplayFunc(display)
43
glutKeyboardFunc(buttons)
44
glutMainLoop()
45
46
if __name__ == "__main__":
47
main()
48
Why this code is not working?
Advertisement
Answer
Define px
and py
in global namespace:
JavaScript
1
9
1
px = 300; py = 300
2
3
def drawPlayer():
4
glColor3f(1,1,0)
5
glPointSize(8)
6
glBegin(GL_POINTS)
7
glVertex2i(px,py)
8
glEnd()
9
Use the 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
to mark the current window as needing to be redisplayed:
JavaScript
1
12
12
1
def buttons(key,x,y):
2
global px, py
3
if key == b'a':
4
px -= 5
5
if key == b'd':
6
px += 5
7
if key == b'w':
8
py -= 5
9
if key == b's':
10
py += 5
11
glutPostRedisplay()
12
Complete example
JavaScript
1
50
50
1
from OpenGL.GL import *
2
from OpenGL.GLU import *
3
from OpenGL.GLUT import *
4
import sys
5
import math
6
7
px = 300; py = 300
8
9
def drawPlayer():
10
glColor3f(1,1,0)
11
glPointSize(8)
12
glBegin(GL_POINTS)
13
glVertex2i(px,py)
14
glEnd()
15
16
def display():
17
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
18
drawPlayer()
19
glutSwapBuffers()
20
21
# Here is my keyboard input code
22
def buttons(key,x,y):
23
global px, py
24
if key == b'a':
25
px -= 5
26
if key == b'd':
27
px += 5
28
if key == b'w':
29
py -= 5
30
if key == b's':
31
py += 5
32
glutPostRedisplay()
33
34
def init():
35
glClearColor(0.3,0.3,0.3,0)
36
gluOrtho2D(0,1024,512,0)
37
38
def main():
39
glutInit(sys.argv)
40
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
41
glutInitWindowSize(1024, 512)
42
window = glutCreateWindow("Raycaster in python")
43
init()
44
glutDisplayFunc(display)
45
glutKeyboardFunc(buttons)
46
glutMainLoop()
47
48
if __name__ == "__main__":
49
main()
50