【发布时间】:2019-10-31 16:04:39
【问题描述】:
我正在用 OpenGL 制作一个游戏,其中一些物体会朝向你。为此,我必须获取当前的相机位置。我知道在 OpenGL 中相机总是停留在 (0,0,0) 位置,但我想根据世界获取相机的当前位置。我该怎么做>
我试过viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
camera_pos = viewMatrix[3],但是我的相机有俯仰和偏航,而且当我这样做时位置总是会改变。我该如何解决这个问题?
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import math,random
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if event.key == pygame.K_p:
paused = not paused
if not paused:
if event.type == pygame.MOUSEMOTION:
mouseMove = [event.pos[i] - displayCenter[i] for i in range(2)]
pygame.mouse.set_pos(displayCenter)
pygame.mouse.set_visible(False)
if not paused:
#Get keys
keypress = pygame.key.get_pressed()
#Init model view matrix
glLoadIdentity()
#------------------------View------------------------
#Apply the look up and down (with 90° angle limit)
if up_down_angle < -90:
if mouseMove[1] > 0:
up_down_angle += mouseMove[1]*0.1
elif up_down_angle > 90:
if mouseMove[1] < 0:
up_down_angle += mouseMove[1]*0.1
else:
up_down_angle += mouseMove[1]*0.1
glRotatef(up_down_angle, 1.0, 0.0, 0.0)
#Init the view matrix
glPushMatrix()
glLoadIdentity()
#Apply the movement
if keypress[pygame.K_w]:
glTranslatef(0,0,0.1)
if keypress[pygame.K_s]:
glTranslatef(0,0,-0.1)
if keypress[pygame.K_d]:
glTranslatef(-0.1,0,0)
if keypress[pygame.K_a]:
glTranslatef(0.1,0,0)
#Apply the look left and right
glRotatef(mouseMove[0]*0.1, 0.0, 1.0, 0.0)
#------------------------View------------------------
#------------------------Draw------------------------
#Multiply the current matrix by the new view matrix and store the final view matrix
glMultMatrixf(viewMatrix)
viewMatrix = glGetFloatv(GL_MODELVIEW_MATRIX)
camera_pos = viewMatrix[3] #Incorrect
print(camera_pos) #print the output
#Apply view matrix
glPopMatrix()
glMultMatrixf(viewMatrix)
glLightfv(GL_LIGHT0, GL_POSITION, [1, -1, 1, 0])
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glPushMatrix()
glColor4f(0.2, 0.2, 0.5, 1)
for person in persons:
person.draw()
ground.draw()
glutSwapBuffers()
glPopMatrix()
#------------------------Draw------------------------
pygame.display.flip()
pygame.time.wait(10)
pygame.quit()
我希望当我进行视图旋转时,我的坐标不会移动,但是这样做时 camera_pos 的输出会发生变化。
【问题讨论】:
标签: python-3.x opengl pygame pyopengl