M
M
Maxim Siomin2020-06-16 11:19:58
Python
Maxim Siomin, 2020-06-16 11:19:58

How to keep track of time in python?

There are shotguns in the 2d shooter on pygame. They have a low rate of fire, how to make sure that a shot can only be fired a second after the previous one. In general, the question is: how to detect a second so that during this very second not everything stops, but other processes work?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Developer, 2020-06-16
@MaxSiominDev

Remember the time of a successful shot.
When you try to shoot again, take the current time and compare it with the time of the last shot

R
Ruslan, 2020-06-16
@DollaR84

I think methods for working with the time of pygame itself are well suited here:
pygame.time
There are 2 ways for your task.
I will give small examples for triggering every 5 seconds, so that it is clearer how easy it is to scale for any time.
1 way. Use a timer.

# при выстреле ставим запрет на следующий выстрел
self.timer = 0 # обнуляем начальное значение для отсчета
pygame.time.set_timer(pygame.USEREVENT, 1000) # запускаем таймер (в милисекундах) на срабатывание каждую секунду
затем в обработчике событий:
for event in pygame.event.get():
    if event.type == pygame.USEREVENT:
        self.timer += 1 # считаем количество пройденных секунд
        if self.timer == 5: # если прошло 5 секунд
            pygame.time.set_timer(pygame.USEREVENT, 0) # отключаем таймер
            # даем разрешение на следующий выстрел

2 way. Use ticks to keep track of time.
# при выстреле ставим запрет на следующий выстрел
self.start_ticks = pygame.time.get_ticks() # запоминаем начальное значение тиков в милисекундах
затем в обработчике событий:
for event in pygame.event.get():
    if event.type == ...: # тут какое-то ваше событие на выстрел
        seconds= (pygame.time.get_ticks() - self.start_ticks)/1000 # вычисляем сколько прошло секунд
        if seconds > 5: # проверяем что прошло 5 секунд
            # даем разрешение на следующий выстрел

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question