Reputation: 664
Making a quick program in which a user shoots at a moving target on the opposite side of the screen. The user can miss the target 3 times and then the game is over. I'm detecting the misses and add them to the total accordingly but when there is a collision between the target and bullet (a hit!) I subtract from the total essentially resetting it. Now I'm only expecting it to subtract "1" but for some reason it's subtracting a bunch and messing everything up. Any ideas as to why this is happening and is there a better way to do this? Target is a pygame.Rect, bullets are Sprites, and ship is an image.
def update_bullets(ai_settings, screen, stats, ship, bullets, target):
bullets.update()
for bullet in bullets.copy():
if bullet.rect.left >= ai_settings.screen_width:
bullets.remove(bullet)
stats.number_of_misses += 1
check_bullet_target_collisions(ai_settings, screen, stats, ship, bullets, target)
if stats.number_of_misses >= stats.max_number_of_misses:
stats.number_of_misses = 0
stats.game_active = False
bullets.empty()
pygame.mouse.set_visible(True)
def check_bullet_target_collisions(ai_settings, screen, stats, ship, bullets, target):
bullet_hit = pygame.sprite.spritecollideany(target, bullets)
if bullet_hit:
print("how many times")
stats.number_of_misses -= 1
Upvotes: 1
Views: 154
Reputation: 438
If I understand what is happening correctly, when the bullet is colliding with the target it is doing so on every frame that it is colliding. If it collides with the target over ten frames then it is going to subtract 1 ten times.
A solution to this would be to destroy the target after it collides on the first frame of the collision, or to destroy the bullet on the first collision.
Turning the targets into simple sprites and replacing
bullet_hit = pygame.sprite.spritecollideany(target, bullets)
with bullet_hit = pygame.sprite.spritecollide(target, bullets, True)
Should "destroy" the bullet by removing it from the sprite group. This may not be applicable to your program but it should hopefully give an idea of what's causing the issue (multiple collisions from the same bullet on the same target).
Upvotes: 2