碰撞功能无法正常工作

the collision function is not working properly

有一个“玩家”(精灵)和一组墙(other_group),也是精灵。使用不相同的 x/y 坐标创建墙时,sprite.spritecollide 方法无法正常工作。水平方向一切正常,垂直方向玩家只是掉进了墙里。 fullcode

class Tile(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__(other_group)
        self.image = wall_images
        self.rect = self.image.get_rect().move(x, y)

# player
class Player(pygame.sprite.Sprite):
    def __init__(self, speed, x, y):
        super().__init__(player_group)
        self.speed = speed
        self.frames = []
        self.cur_frame = 0
        self.image = animation_down[0]
        self.rect = self.image.get_rect().move(x, y)
        self.rect.x = x
        self.rect.y = y

    def possibility_of_movement(self, directory_of_movement):
        if directory_of_movement == 'right':
            tester = Player(self.speed, self.rect.x + self.speed, self.rect.y)
        elif directory_of_movement == 'left':
            tester = Player(self.speed, self.rect.x - self.speed, self.rect.y)
        elif directory_of_movement == 'up':
            tester = Player(self.speed, self.rect.y - self.speed, self.rect.x)
        else:
            tester = Player(self.speed, self.rect.y + self.speed, self.rect.x)

        if pygame.sprite.spritecollide(tester, other_group, dokill=False, collided=pygame.sprite.collide_rect_ratio(0.7)):
            tester.kill()
            return False
        else:
            return True

tile2 = Tile(264, 264)
tile3 = Tile(264+64, 264)
tile4 = Tile(446, 446)
tile4 = Tile(382, 382)

while running:

    if keys[pygame.K_LEFT] and pos_x > 5 and player.possibility_of_movement('left'):
        pos_x -= player.speed
        left = True
        right = False
        down = False
        up = False

我无法对其进行测试,但我认为所有问题都是因为您在创建 tester 时以错误的顺序设置了值 - 它会检查与错误位置的碰撞(与没有任何墙的位置) 而且它不会停止。

对于 up(和 down 类似)您设置 y-speed,x 但您必须设置 x, y-speed

更正 Player()

中值的顺序
elif directory_of_movement == 'up':
    tester = Player(self.speed, self.rect.x, self.rect.y - self.speed)
else:
    tester = Player(self.speed, self.rect.x, self.rect.y + self.speed)