【问题标题】:pygame player collision bugpygame玩家碰撞错误
【发布时间】:2021-05-11 13:45:24
【问题描述】:

我正在制作一个基于图块的 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.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

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

像这样:

1 = tile
0 = player


          0  
111111111


就像平台瓷砖的侧面有看不见的瓷砖。不知道为什么会这样

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    玩家的位置有两个分量,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.rect.y + dy, self.width, self.height):
            # [...]
    

    【讨论】:

    • 当我添加 self.rect + dx 和 self.rect + dy 时,玩家精灵不能向前或向后移动
    • @MakeTheErrorDie 所以你的应用程序中还有更多的错误。我看不到你的完整代码,所以我只能找出明显的地方。
    • 好吧,我发现这个错误是因为我的精灵 png 是一个具有透明背景的字符,所以尺寸是 200x140,并且因为整个图像不是字符,所以它看起来好像字符是浮动的平台外,:/
    • 不确定如何修复它,因为角色左侧有突出部分(例如剑),因此 png 的尺寸必须为 200x140
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多