while done==False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
if event.type == pygame.JOYBUTTONDOWN:
print("Joystick button pressed.")
if event.type == pygame.JOYBUTTONUP:
print("Joystick button released.")
screen.fill(darkgrey)
textPrint.reset()
joystick_count = pygame.joystick.get_count()
textPrint.print(screen, "Number of joysticks: {}".format(joystick_count) )
textPrint.indent()
for i in range(joystick_count):
joystick = pygame.joystick.Joystick(i)
joystick.init()
textPrint.print(screen, "Joystick {}".format(i) )
textPrint.indent()
name = joystick.get_name()
textPrint.print(screen, "Joystick name: {}".format(name) )
axes = joystick.get_numaxes()
textPrint.print(screen, "Number of axes: {}".format(axes) )
textPrint.indent()
for i in range( axes ):
axis = joystick.get_axis( i )
textPrint.print(screen, "Axis {} value: {:>6.0f}".format(i, axis) )
textPrint.unindent()
buttons = joystick.get_numbuttons()
textPrint.print(screen, "Number of buttons: {}".format(buttons) )
textPrint.indent()
for i in range( buttons ):
button = joystick.get_button( i )
textPrint.print(screen, "Button {:>2} value: {}".format(i,button) )
textPrint.unindent()
hats = joystick.get_numhats()
textPrint.print(screen, "Number of hats: {}".format(hats) )
textPrint.indent()
for i in range( hats ):
hat = joystick.get_hat( i )
textPrint.print(screen, "Hat {} value: {}".format(i, str(hat)) )
textPrint.unindent()
pygame.display.flip()
clock.tick(20)
借助在线PyGame文档,我能够生成一个屏幕,显示各个操纵杆的值。我如何将这些值转换为一个事件,该事件说此按钮已被按下,现在执行此操作?
与此类似,
for i in range( axes ):
axis = joystick.get_axis( i )
textPrint.print(screen, "Axis {} value: {:>6.0f}".format(i, axis) )
if Joystick 2's Axis 3 is equal to 1:
print("Joystick 2 is pointing to the right.")
if Joystick 2's Axis 3 is equal to -1:
print("Joystick 2 is pointing to the left.")
textPrint.unindent()
最佳答案
大多数游戏将游戏板输入作为“主循环”的一部分进行处理,“主循环”每帧至少运行一次。如果您具有读取游戏手柄输入的代码,则应将其放在主循环中(可能在顶部附近),然后再进行下一步,以处理输入并更新游戏状态。那是您应该做的事情,例如查看按钮值并决定如何将其转换为游戏动作。游戏状态更新后,您可以重新绘制显示以匹配新的游戏状态并等待下一帧。
您也可以将游戏手柄的输入视为事件并同步处理它们,但是很难做到这一点,因为输入随时可能出现。对于大多数应用程序,最好一次处理所有游戏手柄的输入。如果同步处理输入更改,则应在将更新合并在一起时将其视为独立的更新。例如,当操纵杆移动时,X和Y更改应视为同一输入更改的一部分。如果您不小心,则将它们转换为游戏中的动作时,对其进行单独对待可能会产生阶梯式模式。
关于python - 使用PyGame的操纵杆模块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52457595/