我正在使用一个结合了.colliderect()的for循环来进行碰撞检测,当我尝试用pygame制作一个游戏时,循环变得太慢了,大约有340个墙矩形,我想知道它是不是可以更快,因为它严重影响了游戏循环?
我试过在每一面墙上的不同位置使用坐标点,但只有当你一次移动一定数量的像素时才有效,每移动速度减半,它就会使你保存的坐标点数量增加四倍。
#disregard indent, this is all in an update function that is called every time that a player decides to move.
self._old_position = self.position
PlayerRectangle = pygame.Rect(self.position[0]+ x,self.position[1]+y,16,16)
cwd = os.getcwd()
tmxData = load_pygame(cwd+"\\Maps\\TestfileMap.tmx")
movement = True
for obj in self.walls:
if(pygame.Rect(obj[0],obj[1],16,16).colliderect(PlayerRectangle)):
movement = False
self.move_back()
else:
continue
if movement:
self.position[0] += x
self.position[1] += y
self.stats["position"]=self.position
self.rect.topleft = self.position
self.feet.midbottom = self.rect.midbottom提供的代码可以工作,但是它太慢了,我想知道在碰撞检测中是否有不同的方法,或者如果有一种方法可以使显示的内容更快,它会使事情变得非常麻烦。谢谢
编辑:
所以解决方案基本上是,我有一个load_pygame,它在每次循环时都会运行,只需去掉执行此操作的行,它就会清理更多的东西,为了进一步优化,请更改为每个对象创建Rect的行,只使用已经构造的Rect列表,这限制了函数调用。
发布于 2019-05-06 23:50:21
如果没有一个最小的工作示例,就很难给出自信的建议。
正如我在注释中所说的,有一个对"load_pygame“函数的虚假调用,它似乎读取了代码中的文件数据--这本身就可能是导致速度减慢的原因。此外,在冲突检测中不使用读取的数据。
我没有的另一个建议是让你的墙的矩形预先计算在一个精灵组中,而不是在每次检查时为所有的墙创建新的矩形:pygame.Rect(obj[0],obj[1],16,16).colliderect(PlayerRectangle))。然后你可以使用sprite方法"spritecollideany“-- https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollideany --来优化矩形碰撞验证。
(这也将要求您的播放器对象是Sprite,如果它还不是)。
https://stackoverflow.com/questions/56007376
复制相似问题