我在python中使用OpenGl的代码有问题,我需要控制球在y轴上的移动。球在重力作用下但是当按下按钮时球会跳起来,但是当没有按下球落下 这就像颜色改变/颜色切换游戏。 问题是当我按下按钮一旦球继续向上并按下任何其他按钮它就会下降。
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def KB(Key, x, y):
global pressed
if Key == b"u":
pressed = True
else:
pressed = False
if Key == b"q":
sys.exit()
yy = -0.07
dt = 0.0005
v_velocity = 3
xx = 0
max = False
pressed = False
def drw():
global xx, max, v_velocity, dt, yy, pressed
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT)
glColor(1, 0, 0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslate(xx, 0.4, 0)
glBegin(GL_POLYGON) # The Line
glVertex2d(-0.8, 0.1)
glVertex2d(-0.8, -0.1)
glVertex2d(-0.2, -0.1)
glVertex2d(-0.2, 0.1)
glEnd()
glColor(0, 1, 0)
glBegin(GL_POLYGON) # The Line
glVertex2d(-0.2, 0.1)
glVertex2d(-0.2, -0.1)
glVertex2d(0.4, -0.1)
glVertex2d(0.4, 0.1)
glEnd()
glColor(0, 0, 1)
glBegin(GL_POLYGON)
glVertex2d(0.4, 0.1) # The Line
glVertex2d(0.4, -0.1)
glVertex2d(0.8, -0.1)
glVertex2d(0.8, 0.1)
glEnd()
glLoadIdentity()
glTranslate(0, yy, 0)
glColor(0, 1, 0)
glutSolidSphere(0.07, 25, 25) # The ball
# movement of the Line
if xx > 1.5:
max = True
if xx < -1.5:
max = False
if max:
xx -= 0.0005
else:
xx += 0.0005
# ????? movement of the Ball ???????
if pressed:
yy += 0.0007
else:
v_velocity = v_velocity - 9.8 * dt
yy += v_velocity * dt
glutSwapBuffers()
glutInit()
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE)
glutInitWindowSize(400, 400)
glutCreateWindow(b"Title")
glutDisplayFunc(drw)
glutKeyboardFunc(KB)
glutIdleFunc(drw)
glutMainLoop()
答案 0 :(得分:0)
它被认为是因为你只是在没有按下键时设置重力:
if pressed:
yy += 0.0007
else:
v_velocity = v_velocity - 9.8 * dt
yy += v_velocity * dt
所以按下按钮时,它只会上升,如果没有,它会下降是正常的。
答案 1 :(得分:0)
您必须使用glutKeyboardFunc
功能和glutKeyboardUpFunc
功能。
虽然glutKeyboardFunc
会发出按键被通知的通知,但glutKeyboardUpFunc
会通知已释放密钥。
按下键时设置pressed = True
,释放键时设置pressed = False
。
此外,您应该初始化v_velocity = 0
而不是v_velocity = 3
。
def KBPressed(Key, x, y):
global pressed
if Key == b"p":
pressed = True
if Key == b"q":
sys.exit()
def KBUp(Key, x, y):
global pressed
if Key == b"p":
pressed = False
glutKeyboardFunc(KBPressed)
glutKeyboardUpFunc(KBUp)
注意,您还可以使用特殊键glutSpecialFunc
和glutSpecialUpFunc
e.g。 &#34;向上&#34;键:
def SKUp(Key, x, y):
global pressed
if Key == GLUT_KEY_UP:
pressed = False
def SKPressed(Key, x, y):
global pressed
if Key == GLUT_KEY_UP:
pressed = True
glutSpecialFunc(SKPressed)
glutSpecialUpFunc(SKUp)