繁体   English   中英

python pygame如何反跳按钮?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM