Aris
Aris

Reputation: 75

Pygame time control

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

Upvotes: 1

Views: 656

Answers (2)

Liam
Liam

Reputation: 6429

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)

Upvotes: 1

CorbinMc
CorbinMc

Reputation: 588

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)

Upvotes: 1

Related Questions