代码示范
import pygame # pip install pygame
import pygame.joystick as pyjoystick
pygame.init()
pygame.event.clear() # 清空事件队列
if pyjoystick.get_count() >= 1:
print("操作杆正常")
else:
print("操作杆不存在")
exit()
js = pyjoystick.Joystick(0) # 得到第0个手柄对象
while 1:
event = pygame.event.wait() # 等待事件队列
if event.type == pygame.JOYBUTTONDOWN:
axis = [0]*js.get_numbuttons()
for i in range(0, js.get_numbuttons()):
axis[i] = js.get_button(i)
print(axis)
常用函数
1. 初始化
import pygame # pip install pygame
import pygame.joystick as pyjoystick
pygame.init()
pygame.event.clear() # 清空事件队列
2. 判断设备连接
if pyjoystick.get_count() >= 1:
print("操作杆正常")
else:
print("操作杆不存在")
exit()
3. 等待事件
event = pygame.event.wait() # 等待事件队列
4. 过滤事件
if event.type == pygame.JOYBUTTONDOWN:
if event.type == pygame.JOYBUTTONDOWN and event.dict["button"] == 1 :
if event.type == pygame.JOYAXISMOTION :
if event.type == pygame.JOYAXISMOTION and event.dict["axis"] == 1 :
5. 多键触发
通过事件触发和获取手柄上多个按钮、轴的组合状态,可以实现多键触发。
下面是实现LT、RT、X三键组合触发关闭机器人的功能,其效果为:先将LT、RT按下,再按X键来触发。
js = pyjoystick.Joystick(0) # 得到第0个手柄对象
while 1:
event = pygame.event.wait() # 等待事件队列
if event.type == pygame.JOYBUTTONDOWN:
if event.dict["button"] == 3 and js.get_button(6) == 1 and js.get_button(7) == 1:
do 关闭机器人系统