碰撞检测无法正确报告

时间:2013-04-12 00:48:19

标签: python tkinter

我之前发过关于我正在研究的这个项目(并且你的答案有帮助!)但我仍然有点模糊为什么我的碰撞检测没有正确报告。对于游戏走过的每个图块,它都会返回true,包括当我将玩家角色移动到可碰撞的图块上时。我只是想知道我的碰撞检测算法是否存在问题,或者其他地方是否存在问题。

def checkPlayerEnvCollision(self,player):
    rowCount = 0
    for row in self.cLayer:
        colCount = 0
        for col in row:
            print("col: " + str(col))
            #print(str(self.Level.tileLayer[row][col]) + ": " + str(c[row][col]))
            if col:
                grid_position = (colCount*32, rowCount*32)
                collide_x = False
                collide_y = False

                print(str(grid_position))
                # check x axis for collision
                if player.x + 32 > grid_position[0]:
                    collide_x = True
                elif player.x < grid_position[0] + 32:
                    collide_x = True

                print("Player x: " + str(player.x) + " Player y : " + str(player.y))


                # check y axis for collision
                if player.y < grid_position[1] + 32:
                    collide_y = True
                elif player.y + 32 > grid_position[1]:
                    collide_y = True

                print("collide_x: " + str(collide_x) + " " + "collide_y: "+ str(collide_y))

                # act on a collision on both axis
                if collide_x and collide_y:
                    print("COLLISION DETECTED")
                else:
                    print("NOCOLLISION___")
            colCount += 1
        rowCount += 1

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为代码是这样的:

            if player.x + 32 > grid_position[0]:
                collide_x = True
            elif player.x < grid_position[0] + 32:
                collide_x = True

需要更改为:

            if grid_position[0] + 32 > player.x > grid_position[0]:
                collide_x = True

(是的,这是Python的一个特性,你可以像这样链接比较运算符)