【问题标题】:Pygame time controlPygame时间控制
【发布时间】:2016-09-10 11:05:43
【问题描述】:

我一直在思考如何在 pygame 中控制时间。 即,当 if 语句为 True 时,我希望它为 True 几秒钟, 哪个是最好的 pygame.time-object 使用? 示例

if p.rect.left < self.rect.centerx < p.rect.right and self.rect.bottom >= 560:
            self.kill()

            p.image.fill(red)

这是一个球反弹碰撞,只要这个陈述是真的,我希望它在一段时间内保持真实。我怎样才能做到这一点? :D

【问题讨论】:

    标签: python time pygame


    【解决方案1】:

    试一试。它不是简单地检查您的语句是否评估为True,而是检查它是否在您指定的最后一段时间内评估为True。见Time.time()

    import time
    
    %this is the time in seconds you wish the loop to be treated as true
    timeout = 1.0 
    last_true = -timeout
    
    if (p.rect.left < self.rect.centerx < p.rect.right and self.rect.bottom >= 560):
        last_true = time.time()
    
    if time.time() < last_true + timeout:
        self.kill()
        p.image.fill(red)
    

    【讨论】:

    • 你不应该在pygame中使用时间来计算秒数,而是pygame.time
    • @Liam 如果您要留下该评论,您介意解释一下原因吗?
    • 一个 pygame 游戏可能会滞后并且无法跟随系统时间,并且游戏中的 time.time 秒可能不准确。 pygame.time 更准确。
    【解决方案2】:

    您是否尝试过使用函数pygame.time.get_ticks()

    pygame.time.get_ticks()输出当前滴答数,一个滴答以毫秒为单位。

    它是这样使用的:

    begin = pygame.time.get_ticks()
    
    while pygame_loop:
        time_now = pygame.time.get_ticks()
    
        if time_now-begin > 1000:
            begin=pygame.time.get_ticks()
            statement = True
    

    您的代码将如下所示:

    timeout = 1000
    last_true = -timeout
    
    if (p.rect.left < self.rect.centerx < p.rect.right and self.rect.bottom >= 560):
        last_true = pygame.time.get_ticks()
    
    if pygame.time.get_ticks() < last_true + timeout:
        self.kill()
        p.image.fill(red)
    

    【讨论】:

    • 如果我没心没肺的话,我会因为撞到这个 -1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2019-06-12
    • 2017-03-17
    • 2010-12-07
    • 1970-01-01
    相关资源
    最近更新 更多