Skip to main content
 首页 » 编程设计

Python优化形状重叠检测

2025年05月04日20lyj

我一直在使用 Pygame 在 Python 中开发基于图 block 的平台游戏。将图 block map 变大后,我的性能大幅下降。我使用分析器找到了速度下降的原因,它指出了我用来检查屏幕上有哪些图 block 的列表理解。

[i for i in sprites 
     if (i.rect.x-pos.x)+(WIDTH/2)+i.w>0 
     and (i.rect.x-pos.x)+(WIDTH/2) < WIDTH  
     and (i.rect.y-pos.y)+(HEIGHT/2)+i.h>0 
     and (i.rect.y-pos.y)+(HEIGHT/2) < HEIGHT] 

有什么办法可以优化吗?任何有助于它更快完成任务的事情都会有所帮助。

请您参考如下方法:

将屏幕大小设为矩形并使用内置碰撞检测:

[i for i in sprites if i.rect.colliderect(screen_rect)] 

原来有一个actual function for this没有列表理解,可能会更快:

spritecollide(screen, sprites, True, collided = None)