pygame播放器碰撞错误

问题描述

我正在制作一个基于磁贴的 pygame 平台游戏

这是我的碰撞检查代码

        # check for collision

        for tile in world.tile_list:
            # check for collision in x direction
            if tile[1].colliderect(self.rect.x + dx,self.rect.y,self.width,self.height):
                dx = 0
            # check for collision in y direction
            if tile[1].colliderect(self.rect.x,self.rect.y + dy,self.height):
                # check if below the ground i.e. jumping
                if self.vel_y < 0:
                    dy = tile[1].bottom - self.rect.top
                    self.vel_y = 0
                # check if above the ground i.e. falling
                elif self.vel_y >= 0:
                    dy = tile[1].top - self.rect.bottom
                    self.vel_y = 0

当我运行游戏时,我遇到了一个奇怪的错误,即玩家可以移动到平台图块之外,而玩家应该在离开平台图块时摔倒

像这样:

1 = tile
0 = player


          0  
111111111


就像平台瓷砖的侧面有隐形瓷砖一样。不知道为什么会发生这种情况

解决方法

玩家的位置有两个组成部分,dxdy。玩家当前位置为(self.rect.x + dx,self.rect.y + dy)。这是您在两次碰撞测试中都必须使用的位置:

for tile in world.tile_list:
            
    # check for collision in x direction
    if tile[1].colliderect(self.rect.x + dx,self.rect.y + dy,self.width,self.height):
        # [...]
            
    # check for collision in y direction
    if tile[1].colliderect(self.rect.x + dx,self.height):
        # [...]