【问题标题】:Pygame not returning joystick axis movement without displayPygame不返回没有显示的操纵杆轴运动
【发布时间】:2020-09-12 03:50:40
【问题描述】:

我已经看到这个问题的其他解决方案说您需要调用 pygame.event.pump() 或在 while 循环之外初始化操纵杆。但是,即使使用这些解决方案,我的操纵杆轴值也是 0。

如果我只取消注释 pygame.display.set_mode((1, 1)),那么代码会按预期工作,并且值会输出到控制台。

有没有办法在不创建额外窗口的情况下仍然获得坐标轴值?

另外,我在 Windows 10 上运行 python 3.6。

import pygame

FRAMES_PER_SECOND = 20

pygame.init()
pygame.joystick.init()

# pygame.display.set_mode((1,1))

# Used to manage how fast the screen updates.
clock = pygame.time.Clock()

xboxController = pygame.joystick.Joystick(0)
xboxController.init()


# Loop until the user presses menu button
done = False

print('Found controller\nStarting loop...')
while not done:
    pygame.event.pump()
    for event in pygame.event.get():
        if event.type == pygame.JOYBUTTONDOWN and event.button == 7:
            print(f'Exiting controller loop')
            done = True

    for i in range(xboxController.get_numaxes()):
        print(f'Axis {i}: {xboxController.get_axis(i)}')

    # pygame.display.flip()

    clock.tick(FRAMES_PER_SECOND)

输出:

pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Found controller
Starting loop...
Axis 0: 0.0
Axis 1: 0.0
Axis 2: 0.0
Axis 3: 0.0
Axis 4: 0.0
.
.
.

【问题讨论】:

  • 为什么要在没有窗口的情况下使用 Pygame?它是一个游戏开发框架,沿着这条路走下去感觉充其量是一种 hacky 方式,尤其是在搜索和查看其他人如何破解 Pygame 的问题以及它出现的所有问题之后。也许thisthis 是更好的方法?
  • @Torxed 谢谢!我会检查第二个链接,它似乎也可以做我想做的事。
  • @Torxed 哇,输入库比我想象的要简单得多。在更短的时间内找到更好的解决方案
  • 很高兴它成功了,请记住,对于以后的帖子,您应该允许我们帮助您发布答案,否则您将在提问和撰写文章时获得积分答案,哪种违背了本网站的目的:)
  • @Torxed 哎呀,我的错,刚刚使您的解决方案成为公认的解决方案。再次感谢:)

标签: python pygame display joystick


【解决方案1】:

除非您需要完整的底层GL 功能,否则我可能会离开 Pygame,因为该库是为 2D/3D 游戏开发而设计的。尽管可能将其用于这些目的,但后续问题或多或少是不可避免的。一个可能更简单的方法是使用 python 的 input 库,它可以处理游戏手柄(操纵杆)。

from inputs import get_gamepad

while True:
    events = get_gamepad()
    for event in events:
        if event.ev_type == 'Absolute':
            if event.code == 'ABS_X':
                print(f'Left joystick x: {event.state}')
            elif event.code == 'ABS_Y':
                print(f'Left joystick y: {event.state}')
            elif event.code == 'ABS_RX':
                print(f'Right joystick x: {event.state}')
            elif event.code == 'ABS_RY':
                print(f'Right joystick y: {event.state}')

【讨论】:

    【解决方案2】:

    好吧,在我发布这篇文章 5 分钟后找到了答案。问题是我使用的是 pygame 1.9.6 而不是 2.0.0.dev8。更新后,我得到了没有显示窗口的控制台输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多