我正在制作一款游戏,您必须将物体从一个地方移动到另一个地方。我可以将我的角色移动到我需要放置东西的区域。我希望玩家在将对象放置在那里之前在该区域中等待 5 秒,但是,如果我这样做,如果您决定不想将对象放置在该区域中,则您将无法再移动,因为整个脚本将暂停。
有没有一种方法可以让脚本的一部分在其余部分运行时等待?
最佳答案
每个游戏都需要一个时钟来保持游戏循环同步并控制计时。 Pygame 有一个 pygame.time.Clock
带有 tick()
的对象方法。以下是获得您想要的行为的游戏循环的样子(不是完整的代码,只是一个示例)。
clock = pygame.time.Clock()
wait_time = 0
have_visited_zone = False
waiting_for_block_placement = False
# Game loop.
while True:
# Get the time (in milliseconds) since last loop (and lock framerate at 60 FPS).
dt = clock.tick(60)
# Move the player.
player.position += player.velocity * dt
# Player enters the zone for the first time.
if player.rect.colliderect(zone.rect) and not have_visited_zone:
have_visited_zone = True # Remember to set this to True!
waiting_for_block_placement = True # We're now waiting.
wait_time = 5000 # We'll wait 5000 milliseconds.
# Check if we're currently waiting for the block-placing action.
if waiting_for_block_placement:
wait_time -= dt # Decrease the time if we're waiting.
if wait_time <= 0: # If the time has gone to 0 (or past 0)
waiting_for_block_placement = False # stop waiting
place_block() # and place the block.
关于python - Pygame + python : 1 part of code has pygame. 等待其余代码运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082649/