python - Pygame 不返回操纵杆轴移动而不显示

标签 python pygame display joystick

我见过这个问题的其他解决方案,说你要么需要调用 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,除非您需要整个底层 GL 功能,因为该库适用于 2D/3D 游戏开发。尽管可以将其用于这些目的,但最终的问题或多或少是不可避免的。一个也许更简单的方法是使用 python 的 input库,可以处理游戏 handle (操纵杆)。

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}')

关于python - Pygame 不返回操纵杆轴移动而不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62003575/

相关文章:

python - 将 excel 文件从主目录保存到 Django 中的数据库模型

python - 在管理页面的 collectstatic 没有 css 之后

python - 从数组中删除最大的项目并将其一半添加回相同的位置

python - 左右移动物体

python - Pygame:窗口没有响应

html - 使用 Bootstrap 3 和 flexbox 的等高列

azure - 如何在 Azure VM 上安装 NVIDIA 显卡驱动程序

python - 如何扫描 pandas 行中的第一个非零值并使用数字创建新列

python - 无法运行播放通过 cx_Freeze 编译的 OGG 文件的 Pygame 脚本

html - 无法在一侧设置边框半径,在另一侧设置常规边框