获得正确的玩家碰撞

时间:2021-05-15 06:59:13

标签: python python-3.x pygame

我正在用 pygame 制作一个基于 tile 的 plaformer 游戏。这是我的播放器精灵:

enter image description here

这是碰撞检测器代码:

 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.width, 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

当我如图所示运行游戏时:玩家可以站在平台外, enter image description here

我需要获得正确的玩家宽度,所以当我使用 width = player_png.get_width() 时,我得到了这个图像的总宽度,但我只想要第一条腿到第二条腿的宽度,这样碰撞检测器只会将该宽度视为播放器宽度。

enter image description here

我可以手动将宽度分配给从第一条腿到第二条腿的宽度,但是当我这样做时,碰撞检测器会检测到图像中间的宽度并且没有正确对齐

1 个答案:

答案 0 :(得分:1)

对此没有自动解决方案。您需要为碰撞测试定义一个子区域:

offset_x   = # offset_x is the first distance to the "black" pixel
foot_width = # width of the foots

foot_x = self.rect.x + offset_x 

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
    
    # check if below the ground i.e. jumping
    if self.vel_y < 0:
        if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
            dy = tile[1].bottom - self.rect.top
            self.vel_y = 0

    # check if above the ground i.e. falling
    if self.vel_y >= 0:
        if tile[1].colliderect(foot_x, self.rect.y + dy, foot_width, self.height):
            dy = tile[1].top - self.rect.bottom
            self.vel_y = 0