如何使用pygam识别PS4控制器上按下的按钮

2024-06-06 10:13:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我用一个树莓Pi 3来控制一个机器人车辆。我已经使用ds4drv成功地将PS4控制器链接到RPi。当使用pygame在PS4控制器上按下/释放按钮时,我有以下代码工作并输出“Button Pressed/”Button Released“。我在想如何确定到底是哪个按钮被按下了。

ps4_controller.py

import pygame

pygame.init()

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

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                print("Button Pressed")
            elif event.type == pygame.JOYBUTTONUP:
                print("Button Released")

except keyboardInterrupt:
    print("EXITING NOW")
    j.quit()

Tags: eventinittypepi机器人button控制器events
3条回答

找到一个黑客:

PS4按钮编号如下:

0 = SQUARE

1 = X

2 = CIRCLE

3 = TRIANGLE

4 = L1

5 = R1

6 = L2

7 = R2

8 = SHARE

9 = OPTIONS

10 = LEFT ANALOG PRESS

11 = RIGHT ANALOG PRESS

12 = PS4 ON BUTTON

13 = TOUCHPAD PRESS

为了找出按下的是哪个按钮,我使用了j.get_button(int),传入匹配的按钮整数。

示例:

import pygame

pygame.init()

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

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYBUTTONDOWN:
                print("Button Pressed")
                if j.get_button(6):
                    # Control Left Motor using L2
                elif j.get_button(7):
                    # Control Right Motor using R2
            elif event.type == pygame.JOYBUTTONUP:
                print("Button Released")

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()
if event.type == pygame.JOYBUTTONDOWN:
        if j.get_button(0):
            PXV = -0.1
        if j.get_button(2):
            PXV = 0.1
    if event.type == pygame.JOYBUTTONUP:
        if j.get_button(0) or j.get_button(2):
            PXV = 0

joy button down工作,但PXV(播放器x速度) 当我释放控制器时不会重置回零

你真的很亲近!只要稍加调整,代码就会变成:

import pygame

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

try:
    while True:
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.JOYAXISMOTION:
                print(event.dict, event.joy, event.axis, event.value)
            elif event.type == pygame.JOYBALLMOTION:
                print(event.dict, event.joy, event.ball, event.rel)
            elif event.type == pygame.JOYBUTTONDOWN:
                print(event.dict, event.joy, event.button, 'pressed')
            elif event.type == pygame.JOYBUTTONUP:
                print(event.dict, event.joy, event.button, 'released')
            elif event.type == pygame.JOYHATMOTION:
                print(event.dict, event.joy, event.hat, event.value)

except KeyboardInterrupt:
    print("EXITING NOW")
    j.quit()

我发现的一些资源有助于编写up-includedpygame's event documentation,使用python的dir函数查看python对象具有哪些属性,以及documentation for pygame's parent C library, SDL(如果您想更深入地解释该属性的实际含义)。我包括字典访问版本(使用event.dict)和属性访问版本(仅使用event.whatever_the_property_name_is)。请注意,event.button只给您一个数字;由您手动创建每个按钮数字在控制器上的含义的映射。希望这能解决问题!

相关问题 更多 >