如何解决PYGAME:为什么在游戏循环内调用游戏循环内的函数会使我的游戏滞后?
我正在制作一个简单的游戏,敌人在屏幕上四处移动,我们需要射击他们。我想模块化我的代码,所以我想用一个函数替换游戏循环逻辑。但是一旦我这样做了, fps 有所下降。在 while 循环中调用函数会降低 fps 吗?
不使用函数,我的游戏循环是:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
crosshair.shoot()
pygame.display.update()
#blit bg
displaysurf.blit(background,(0,0))
#render group of sprites
target_group.draw(displaysurf)
crosshair_group.draw(displaysurf)
#call the update methods
crosshair_group.update()
target_group.update()
#display fps
#print(clock.get_fps())
#restrict to 60frames drawing per second
clock.tick(60)
带函数:
def first_level():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
crosshair.shoot()
pygame.display.update()
#blit bg
displaysurf.blit(background,0))
#render group of sprites
target_group.draw(displaysurf)
crosshair_group.draw(displaysurf)
#call the update methods
crosshair_group.update()
target_group.update()
#display fps
#print(clock.get_fps())
#restrict to 60frames drawing per second
clock.tick(60)
while True:
first_level()
但是在我添加这个功能的那一刻,我的游戏开始因为 FPS 降低而卡顿。为什么会发生这种情况?
解决方法
看起来你弄乱了缩进。 pygame.display.update()
以及之后的所有内容都不应成为 for event ...
循环的一部分。
def first_level():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
crosshair.shoot()
pygame.display.update()
#blit bg
displaysurf.blit(background,(0,0))
#render group of sprites
target_group.draw(displaysurf)
crosshair_group.draw(displaysurf)
#call the update methods
crosshair_group.update()
target_group.update()
#display fps
#print(clock.get_fps())
#restrict to 60frames drawing per second
clock.tick(60)
while True:
first_level()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。