2016-06-10 19 views
0

所以即時建立一個基於pi的機器人。 它使用ps3控制器進行輸入。當按下X按鈕時,它會拍攝照片。出於某種原因,一次只需要5次左右的拍攝。有沒有辦法反彈輸入,以便只識別一次按鍵?python pygame如何去除按鈕?

我假設它的註冊多個印刷機每次...部分代碼連接,但我必須說明大部分是從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() 
+0

你可以阻止一個以上的調用'take_picture()'直到你得到一個'JOYBUTTONUP' – Tomer

+0

有意思,你能解釋更多嗎?即時通訊全新的pygame /使用按鈕和即時通訊相當新的python ...這是我的第一個大項目!你會簡單地'如果event.type == pygame.JOYBUTTONUP:'在'take_picture()'之前? – JONAS402

+0

是的,只有釋放按鈕時,纔會拍照。 – Tomer

回答

1

什麼似乎是發生的是X按鈕停留多個幀。在此期間可能會發生其他一些事件,導致在您的代碼中每幀調用take_picture()。要解決這個問題,您只能在JOYBUTTONUP(釋放按鈕時)撥打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 
+0

真正完美的解釋!非常感謝你甚至包括變量選項。我正在思考這些問題,但是我不知道如何添加'and not'語句!希望我能給你買一杯啤酒! – JONAS402