Tank collides with walls in pygame

前端 未结 1 861
名媛妹妹
名媛妹妹 2021-01-27 02:49

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 the tank stop when it collides with the wal

相关标签:
1条回答
  • 2021-01-27 03:39

    Tank is a Sprite object. The walls are Sprite objects, too and collected in the Group wall_list. Thus you can use pygame.sprite.spritecollide() to detect a collision:

    if pygame.sprite.spritecollide(self.tank, self.wall_list, False):
        print("tank collides with wall")
    

    Note, pygame.sprite.spritecollide() returns a list of the Wall objects, which caused the collision. In your case the list will probably contain 1 element when the tank collides:

    hit_walls = pygame.sprite.spritecollide(self.tank, self.wall_list, False)
    if hit_walls:
        hit_wall = hit_walls[0]
    

    Alternatively you can iterate through the walls, which caused the collision:

    for hit_wall in pygame.sprite.spritecollide(self.tank, self.wall_list, False):
        # [...]
    

    For instance you can cancel the movement of the tank, when it hits a wall in Game.handle_events:

    class Game:
        # [...]
    
        def handle_events(self):
    
            tank_pos = pygame.math.Vector2(self.tank.pos)
            self.tank.handle_events()
            if pygame.sprite.spritecollide(self.tank, self.wall_list, False): 
                self.tank.pos = tank_pos
                self.tank.rect.center = round(tank_pos[0]), round(tank_pos[1])
    
            # [...] 
    
    0 讨论(0)
提交回复
热议问题