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
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])
# [...]