本文介绍了如何使用pygame识别在PS4控制器上按下哪个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Raspberry Pi 3 来控制机器人车辆.我已经使用 ds4drv 成功地将我的 PS4 控制器连接到 RPi.当使用 pygame 在 PS4 控制器上按下/释放按钮时,我有以下代码工作并输出按钮按下"/按钮释放".我想知道如何确定哪个按钮正在被按下.

I am using a Raspberry Pi 3 to control a robotic vehicle. I have successfully linked my PS4 controller to the RPi using ds4drv. I have the following code working and outputting "Button Pressed"/"Button Released" when a button is pressed/released on the PS4 controller using pygame. I am wondering how to identify which button is exactly being pressed.

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()

推荐答案

想出了一个 hack:

Figured out a hack:

PS4 按钮编号如下:

The PS4 buttons are numbered as the following:

0 = SQUARE

1 = X

2 = CIRCLE

3 = 三角形

4 = L1

5 = R1

6 = L2

7 = R2

8 = SHARE

9 = 选项

10 = 左模拟按键

11 = 右模拟按键

12 = PS4 开启按钮

13 = 触控板按压

为了确定哪个按钮被按下,我使用了 j.get_button(int),传入匹配的按钮整数.

To figure out which button is being pressed I used j.get_button(int), passing in the matching button integer.

示例:

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()

这篇关于如何使用pygame识别在PS4控制器上按下哪个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 02:53