然后,加上用键盘控制小球的方向的代码
时间: 2024-03-16 17:44:18 浏览: 141
python+pygame利用键盘方向键移动小球
好的,接下来我来为你添加控制小球方向的代码。
```python
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
vertices = (
(1, -1, -1),
(1, 1, -1),
(-1, 1, -1),
(-1, -1, -1),
(1, -1, 1),
(1, 1, 1),
(-1, -1, 1),
(-1, 1, 1)
)
edges = (
(0, 1),
(0, 3),
(0, 4),
(2, 1),
(2, 3),
(2, 7),
(6, 3),
(6, 4),
(6, 7),
(5, 1),
(5, 4),
(5, 7)
)
def Cube():
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(vertices[vertex])
glEnd()
def main():
pygame.init()
display = (800,600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glTranslatef(0.0,0.0, -5)
x = 0
y = 0
z = 0
speed = 0.1
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x = speed
elif event.key == pygame.K_RIGHT:
x = -speed
elif event.key == pygame.K_UP:
y = -speed
elif event.key == pygame.K_DOWN:
y = speed
elif event.key == pygame.K_w:
z = speed
elif event.key == pygame.K_s:
z = -speed
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y = 0
elif event.key == pygame.K_w or event.key == pygame.K_s:
z = 0
glTranslatef(x, y, z)
glRotatef(1, 3, 1, 1)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
Cube()
pygame.display.flip()
pygame.time.wait(10)
if __name__ == '__main__':
main()
```
在这个代码中,我们添加了一些变量来控制小球的移动速度和方向,然后根据按键事件来改变小球的位置。你可以尝试修改速度值,或者添加其他按键事件来控制小球的运动。
阅读全文