Pygame time control

霸气de小男生 提交于 2020-01-06 02:50:00

问题


I've been thinking in pygame how can i control time. Namely, when an if-statement is True , i want it True just for some seconds, Which is the best pygame.time-object to use? Example

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

            p.image.fill(red)

This is a ball bounce-collision and whenever this statement is True i want it to stay True just for an amount of time. How can I do that? :D


回答1:


have you tried using the function pygame.time.get_ticks()?

pygame.time.get_ticks() outputs the current tick number, a tick is represented in milliseconds.

it is used like this:

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

and your code will look like this:

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)



回答2:


Give this a shot. Instead of simply checking if your statement evalueate to True, it checks if it's been evaluated to True within the last certain period of time that you specify. See 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)


来源:https://stackoverflow.com/questions/37223752/pygame-time-control

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!