2015-09-27 243 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