python - Pygame + python:1 部分代码有 pygame.wait 而其余代码运行
问题描述
我正在制作一个游戏,你必须将移动物体从一个地方带到另一个地方。我可以将我的角色移动到我需要放置东西的区域。我希望玩家在该区域等待 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.
推荐阅读
- reactjs - 反应路由器不显示页面
- sql - 删除有条件的表 - Oracle
- ios - 当应用程序处于后台时,使用 CXAnswerCallAction 请求事务时出错
- javascript - 如果 FullCalendar 4 在从 datesRender 事件加载数据时仅显示当前月份错误的事件?
- uwp - 如何自动增加在 Azure Pipeline 中创建的 .msixupload 文件的包版本号?
- javascript - 除了使用 Axios 和 NodeJS 的文件之外,FormData 不会附加其他变量
- javascript - Javascript 无法在刷新时立即从 getElementById 读取值
- python - 使用 windowsapi reloader 重启
- powerbi - 星型模式的断开连接表中过滤器的奇怪行为
- python-3.x - Python:尝试删除生成以发送电子邮件附件的文件时出错