我有一个使用OpenGL创建的立方体场,并且可以正常移动,部分旋转"相机"也正常工作,但当我尝试向上或向下看时出现问题。
我有一小段代码有点可用:
if pressed[pygame.K_UP] or pressed[pygame.K_DOWN]:
rotx = cos(rot/radian)
rotz = sin(rot/radian)
if pressed[pygame.K_UP]:
glRotatef(speed / 2, -rotx, 0, rotz)
if pressed[pygame.K_DOWN]:
glRotatef(speed / 2, rotx, 0, -rotz)
但只有当旋转角度为0时才有效。因此,当我第一次运行程序时,我只能左右移动,如果不向左或向右看,也不向前或向后移动。
verticies = (
(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(tX, tY, tZ):
glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3f(verticies[vertex][0] + tX, verticies[vertex][1] + tY, verticies[vertex][2] + tZ)
glEnd()
def main():
pygame.init()
screenSize = (1500, 800)
pygame.display.set_mode(screenSize, DOUBLEBUF|OPENGL)
gluPerspective(45, (screenSize[0]/screenSize[1]), 0.1, 50.0)
rot = 0
speed = 3
radian = 57.2958
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pressed = pygame.key.get_pressed()
#==# Rotation with arrow keys #==#
if pressed[pygame.K_LEFT]:
glRotatef(speed / 2, 0, -1, 0)
rot += 1
if pressed[pygame.K_RIGHT]:
glRotatef(speed / 2, 0, 1, 0)
rot -= 1
if pressed[pygame.K_UP] or pressed[pygame.K_DOWN]:
rotx = cos(rot/radian)
rotz = sin(rot/radian)
if pressed[pygame.K_UP]:
glRotatef(speed / 2, -rotx, 0, rotz)
if pressed[pygame.K_DOWN]:
glRotatef(speed / 2, rotx, 0, -rotz)
#==# Walking with WASD #==#
if pressed[pygame.K_w]:
glTranslate(sin(rot/radian) / speed, 0, cos(rot/radian) / speed)
if pressed[pygame.K_s]:
glTranslate(-sin(rot/radian) / speed, 0, -cos(rot/radian) / speed)
if pressed[pygame.K_a]:
glTranslate(sin((rot + 90)/radian) / speed, 0, cos((rot + 90)/radian) / speed)
if pressed[pygame.K_d]:
glTranslate(-sin((rot + 90)/radian) / speed, 0, -cos((rot + 90)/radian) / speed)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
for i in range(8):
for j in range(8):
Cube(-i*2.5, -4, -j*2.5)
pygame.display.flip()
pygame.time.wait(10)
main()
我曾认为这可以作为FPS游戏中的移动和相机,但实际证明并不可行。