Pygame在没有显示的情况下不返回操纵杆轴运动

问题描述 投票:1回答:2

我已经看到其他解决方案,您需要调用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
.
.
.
python pygame display joystick
2个回答
1
投票

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


0
投票

除非您需要整个底层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}')
© www.soinside.com 2019 - 2024. All rights reserved.