How does bullet reflect of the wall

前端 未结 1 1896
逝去的感伤
逝去的感伤 2021-01-26 04:09

I\'ve been working on this project about tanks (based on game Tank Trouble) and I\'ve made walls appear on the screen. How can I make that when projectiles/bullets collide with

相关标签:
1条回答
  • 2021-01-26 04:36

    I have a solution. First check for a collision with bullet.rect.colliderect(wall.rect), then check if the center of the bullet is left of the wall, then it must be colliding on the left side, using this logic, you can do the same for the other sides.

    So in the bullet update, i added:

    for wall in game.wall_list:
         if self.rect.colliderect(wall.rect): #if collided
             if self.rect.centerx < wall.rect.left: 
                 self.direction.x *= -1
                 self.rect.right = wall.rect.left
                 self.lives -= 1
                 if self.lives == 0:
                     return self.kill()    
                 break # break so dont check every other wall
             if self.rect.centerx > wall.rect.right:
                 self.direction.x *= -1
                 self.rect.left = wall.rect.right
                 self.lives -= 1
                 if self.lives == 0:
                     return self.kill()    
                 break  
             if self.rect.centery < wall.rect.top:
                 self.direction.y *= -1
                 self.rect.bottom = wall.rect.top
                 self.lives -= 1
                 if self.lives == 0:
                     return self.kill()    
                 break    
             if self.rect.centery > wall.rect.bottom:
                 self.direction.y *= -1
                 self.rect.top = wall.rect.bottom
                 self.lives -= 1
                 if self.lives == 0:
                     return self.kill()    
                 break 
    
    0 讨论(0)
提交回复
热议问题