Pygame矩形碰撞

时间:2015-09-27 17:08:13

标签: python python-3.x pygame

我的碰撞代码存在错误,我似乎无法找到问题所在。当我的角色与顶部块面碰撞时,该算法检测到我也与左侧碰撞。

因此,实际上,由于错误的碰撞检测,我无法向右移动,有时会离开。

def BlockCollision(self, vector):

    pos           = self.GetPos()
    predicted_pos = Vector.Add(pos, self.GetVelocity())

    top           = predicted_pos[1] - (self.Entity.h / 2)
    bottom        = predicted_pos[1] + (self.Entity.h / 2)
    left          = predicted_pos[0] - (self.Entity.w/2)
    right         = predicted_pos[0] + (self.Entity.w/2)


    collision_direction = "NaN"

    for k, v in enumerate(ents.FindByClass("block")):

        ent     = ents.FindByClass("block")[k]
        ent_pos = ent.GetPos()

        block_top, block_bottom = ent_pos[1] - (1/2 * ent.Entity.h),  ent_pos[1] + (1/2 * ent.Entity.h)
        block_left, block_right = ent_pos[0] - (1/2 * ent.Entity.w),  ent_pos[0] + (1/2 * ent.Entity.w)

        colliding_left_noz, colliding_right_noz = (predicted_pos[0] < ent_pos[0] and (right > block_left and right < block_right)), ( not(predicted_pos[0] < ent_pos[0]) and (left > block_left and left < block_right))
        colliding_left, colliding_right = colliding_left_noz and (bottom > block_top and bottom < block_bottom) or (top > block_top and top < block_bottom), colliding_right_noz and (bottom > block_top and bottom < block_bottom) or (top > block_top and top < block_bottom)

        colliding_top_nox, colliding_bottom_nox = (predicted_pos[1] < ent_pos[1]) and (bottom > block_top and bottom < block_bottom), not(predicted_pos[1] < ent_pos[1]) and (top > block_top and top < block_bottom)
        colliding_top, colliding_bottom = colliding_top_nox and ((right > block_left and right < block_right) or (left > block_left and left < block_right)), colliding_bottom_nox and ((right > block_left and right < block_right) or (left > block_left and left < block_right))



        if colliding_left:

            if self.Velocity[0] > 0:
                self.Velocity = [0, self.Velocity[1]]
            else:
                pass
        elif colliding_right:

            if self.Velocity[0] < 0:
                self.Velocity = [0, self.Velocity[1]]
            else:
                pass
        if colliding_top:

            if self.Velocity[1] > 0:
                self.Velocity = [self.Velocity[0], 0]
            else:
                pass
        elif colliding_bottom:

            if self.Velocity[1] < 0:
                self.Velocity =[self.Velocity[0], 0]
            else:
                pass

所以有人知道它有什么问题吗?

1 个答案:

答案 0 :(得分:0)

在计算colliding_leftcolliding_right时,您忘记了第2和第3条款的括号。您正确执行了colliding_topcolliding_bottom