延迟操纵杆

2024-03-29 05:03:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码由一个更新变量的PyGame模块组成self.mm计数当左斗杆的垂直轴移动时。我的问题是它过于频繁地更新mmcount变量,以至于很难得到一个特定的整数。我认为解决方法是在IF语句中添加一个延迟。例如,每两秒钟检查一次左斗杆是否朝上。你知道吗

这些是更新self.mm计数变量:

if joy1.get_button(3) == 1:
    self.mmcount -= 1
if joy1.get_button(2) == 1:
    self.mmcount += 1

完整代码:

class Menu:
    def run(self):
        self.intro = True
        self.clock = clock
        self.mmcount = 1
            while self.intro:
                self.get_joys()

    def get_joys(self):
        if joy1.get_button(3) == 1:
            self.mmcount -= 1
        elif joy1.get_button(2) == 1:
            self.mmcount += 1

        if self.mmcount > 3:
            self.mmcount = 3
        elif self.mmcount < 1:
            self.mmcount = 1

m = Menu()
while True:
    m.run()

Tags: run代码selftruegetifdefbutton
1条回答
网友
1楼 · 发布于 2024-03-29 05:03:03

你需要一个定时器来控制速度。我只使用delta timeself.dt)返回的clock.tick来增加self.mmcount_timer变量。0.2秒后,我增加self.mmcount并重置计时器。你知道吗

顺便说一下,您可以用这种方式钳制值:self.mmcount = max(min(30, self.mmcount), 1)。你知道吗

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
joysticks = [pg.joystick.Joystick(x) for x in range(pg.joystick.get_count())]
for joystick in joysticks:
    joystick.init()


class Menu:

    def run(self):
        self.intro = True
        self.clock = clock
        self.mmcount = 1
        self.mmcount_timer = 0
        self.dt = 0

        while self.intro:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.intro = False
            self.get_joys()

            screen.fill(BG_COLOR)
            pg.display.flip()
            self.dt = clock.tick(60) / 1000

    def get_joys(self):
        if len(joysticks) >= 1:
            if joysticks[0].get_button(3):
                # Increment the timer variable.
                self.mmcount_timer += self.dt
                # If 0.2 seconds have passed.
                if self.mmcount_timer >= .2:
                    # Decrement the count variable.
                    self.mmcount -= 1
                    # And reset the timer.
                    self.mmcount_timer = 0
            elif joysticks[0].get_button(2):
                self.mmcount_timer += self.dt
                if self.mmcount_timer >= .2:
                    self.mmcount += 1
                    self.mmcount_timer = 0
            # Clamp the value between 1 and 30.
            self.mmcount = max(min(30, self.mmcount), 1)
            # Set the title to the mmcount.
            pg.display.set_caption(str(self.mmcount))


Menu().run()
pg.quit()

相关问题 更多 >