奇怪的走过墙壁虫,碰撞系统pygame

时间:2016-04-06 14:14:02

标签: python pygame

def checkCollision(self):
        for entity in self.Entities:
            ox = entity.x
            oy = entity.y
            for block in self.Blocks:

                if block.y < entity.y and entity.y < block.y + block.size:
                    if (entity.x < block.x and block.x < entity.x+entity.width) or (entity.x+entity.width > block.x+block.size and block.x+block.size > entity.x):
                        print ("Hit Bottom")
                        entity.tpEntity(ox, oy+0.5)
                elif entity.y < block.y and block.y < entity.y+entity.height:
                    if (entity.x < block.x and block.x < entity.x+entity.width) or (entity.x+entity.width > block.x+block.size and block.x+block.size > entity.x):
                        print ("Hit Top")
                        entity.tpEntity(ox, oy-self.gravity)
                elif entity.x < block.x and block.x < entity.x+entity.width:
                    if (block.y < entity.y and entity.y < block.y + block.size) or (entity.y < block.y and block.y < entity.y+entity.height):
                        print("Hit Left")
                        entity.tpEntity(ox-0.5,oy)
                elif entity.x+entity.width > block.x+block.size and block.x+block.size > entity.x:
                    if (block.y < entity.y and entity.y < block.y + block.size) or (entity.y < block.y and block.y < entity.y+entity.height):
                        print("Hit Right")
                        entity.tpEntity(ox+0.5,oy)

我有这个奇怪的错误,如果我走到墙上,它总是把它记录在它的顶部。任何人都可以向我解释为什么会发生这种情况,以及我应该如何/可以解决它?谢谢:))

编辑:self.gravity变量是行星/地图上的重力,因为它应该在每个行星/地图上不同。默认情况下(此处)为0.2。

1 个答案:

答案 0 :(得分:0)

我假设实体和块是类?如果您使用pygame.Rect对象设置每个对象,并在实体移动时更新它,您可以通过执行以下操作来简化:

def checkCollision(self):
    for entity in self.Entities:
        ox = entity.x
        oy = entity.y
        for block in self.Blocks:
            if entity.rect.colliderect(block.rect):

然后测试x和y位置以确定反射。