2015-09-27 158 views
0

我有一个我的碰撞代码的错误,我似乎无法找到问题。当我的角色与顶部块面碰撞时,算法检测到我也与左侧碰撞。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 

因此,没有人知道什么是错呢?

回答

0

计算colliding_leftcolliding_right时,您忘记了第2和第3个子句的括号。你正确地做了colliding_topcolliding_bottom