Skip to main content
 首页 » 编程设计

Python、Pygame 和碰撞检测效率

2024年11月01日12Terrylee

我正在使用自定义 Sprite 类(不是 pygame.Sprite)制作自上而下的横向滚动瓷砖游戏。

sprite collide() 函数导致帧率下降(我使用了 cProfile)。

请帮我找出问题。

该函数以这种一般方式运行:

def collide(self): 
        for tile in tiles: 
            if tile.type == 'wall': 
                if self.getDist(tile.rect.center) < 250: 
                    if self.rect.colliderect(tile.rect): 
                        return True 
  1. 找到 Sprite 和所有墙砖之间的距离向量很耗时
  2. 我认为只对 250 像素以内的图 block 运行 rect.colliderect() 会更快;但显然不是。
  3. 我没有包括源代码,因为我正在寻找对我的碰撞检测效率低下问题的更多概念性答案。

一种可能的解决方案是为不同的图 block 组(即 wallList、groundList)创建单独的列表,但是,我真的认为我在图 block 对象列表中搜索的方式存在根本问题。

我是 StackOverflow 的新手,如果我的问题结构/缺少源代码冒犯了您,我深表歉意。

请您参考如下方法:

我没有检查 map 中的每个图 block 以进行碰撞检测,而是创建了一个函数来识别 Sprite 的当前图 block ,然后返回它的八个相邻图 block 。 瓦片扫描方法:

def scanTiles(self): 
    m = curMap.map # this is a 2d matrix filled with tile-objects  
    x = int(self.trueX) # trueX & trueY allow me to implement 
    y = int(self.trueY) # a 'camera system' 
    curTile = m[y // T_SIZE[1]][x // T_SIZE[0]]  
    i = curTile.index # (x, y) coordinate of tile on map 
 
    nw = None # northwest 
    n = None # north 
    ne = None # northeast 
    e = None # east 
    se = None # southeast 
    s = None # south 
    sw = None # southwest 
    w = None # west 
 
    # Each if-statement uses map indices 
    # to identify adjacent tiles. Ex: 
    # NW  N  NE 
    # W  CUR  E 
    # SW  S  SE 
 
    if i[0] > 0 and i[1] > 0: 
        nw = m[i[1]-1][i[0]-1] 
    if i[1] > 0: 
        n = m[i[1]-1][i[0]] 
    if i[0] < len(m[0])-1 and i[1] > 0: 
        ne = m[i[1]-1][i[0]+1] 
    if i[0] < len(m[0])-1: 
        e = m[i[1]][i[0]+1] 
    if i[0] < len(m[0])-1 and i[1] < len(m)-1: 
        se = m[i[1]+1][i[0]+1] 
    if i[1] < len(m)-1: 
        s = m[i[1]+1][i[0]] 
    if i[1] < len(m)-1 and i[0] > 0: 
        sw = m[i[1]+1][i[0]-1] 
    if i[0] > 0: 
        w = m[i[1]][i[0]-1] 
    return [nw, n, ne, e, se, s, sw, w] 

最后,在返回相邻图 block 列表后,碰撞函数检查每个图 block 是否与 pygame.Rect.colliderects() 发生碰撞。 碰撞检测方法:

def collide(self, adjTiles): # adjTiles was returned from scanTiles() 
    for tile in adjTiles: 
        if tile:             # if a tile actually exists, it continues 
            if tile.type == 'wall': # tile type can either be 'ground' or 'wall' 
                if self.rect.colliderect(tile.rect1): 
                    return True # if there is a collision, it returns 'True' 

事实证明,这种新方法更加有效,并且暂时解决了我的问题。