[英]python pygame how to debounce a button?
因此,我正在建立一個基於pi的機器人。 它使用ps3控制器進行輸入。 按下X按鈕時,它會拍照。 由於某種原因,一次拍攝約5張照片。 有沒有辦法反彈輸入,使其只能識別一次按動?
我假設每次都在注冊多台印刷機...部分代碼已附加,但我必須聲明大部分代碼都來自piborg.org
joystick = pygame.joystick.Joystick(0)
button_take_picture = 14 # X button
while running:
# Get the latest events from the system
hadEvent = False
events = pygame.event.get()
# Handle each event individually
for event in events:
if event.type == pygame.QUIT:
# User exit
running = False
elif event.type == pygame.JOYBUTTONDOWN:
# A button on the joystick just got pushed down
hadEvent = True
elif event.type == pygame.JOYAXISMOTION:
# A joystick has been moved
hadEvent = True
if hadEvent:
if joystick.get_button(button_take_picture):
take_picture()
似乎正在發生的事是X按鈕停留了多個幀。 在此期間可能還會發生其他一些事件,從而導致在每個幀中調用代碼中的take_picture()
。 要解決此問題,您可以僅在JOYBUTTONUP
(釋放按鈕時take_picture()
上調用take_picture()
,或將if joystick.get_button(button_take_picture)
部分移至pygame.JOYBUTTONDOWN
部分內。
另外,您可以使用另一個變量來指示是否已拍攝照片,如下所示:
picture_was_taken = False
while running:
hadEvent = False
events = pygame.event.get()
for event in events:
...
if event.type == pygame.JOYBUTTONUP:
if not joystick.get_button(button_take_picture)
picture_was_taken = False
...
if hadEvent:
if joystick.get_button(button_take_picture) and not picture_was_taken:
take_picture()
picture_was_taken = True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.