user4813927
user4813927

Reputation:

Pygame sprite.spritecollide()

In the following Test in line 133 onwards i am testing for collision between targets and the bullets. I am wondering why the target_hit_list is allways only one Target object? Is it because target_hit_list gets updated and new assigned in each loop, so it is allways empty as the next collision takes place?

Here is the link to the code.

Upvotes: 0

Views: 341

Answers (3)

emorphus
emorphus

Reputation: 560

pygame has another feature which checks for collisions between all sprites at once. (collidelistall) Try that...

Upvotes: 1

marienbad
marienbad

Reputation: 1453

something like this:

running = True
while running:

    check_events()
    update_player_position()
    collision_check()
    draw_all()

def check_events():

    for e in pygame.event.get():
        if e.type==pygame.QUIT or (e.type==pygame.KEYDOWN and e.key==pygame.K_ESCAPE):
            runs=0
        player.shoot()

def update():

      #logics
    for ahsm in all_have_same_method:
        ahsm.hanging()

    all_have_same_method.update()


def collision_check():

    for b in bullet_group:
        target_hit_list=pygame.sprite.spritecollide(b,target_group,0)
        for thl in target_hit_list:
            score+=1
        print target_hit_list #why is in the target_hit_list allways only one Target object? 

def draw():
    #drawings
    #draw score
    draw_score=font.render(str(score),True,RED)
    screen.fill(BLACK,(0,0,50,20))
    screen.set_colorkey(BLACK)
    screen.blit(draw_score,(0,0))

    all_have_same_method.draw(screen)

Upvotes: 1

marienbad
marienbad

Reputation: 1453

Yes. Also the bullet only collides with one target. Also you should separate the code out, so you have a main loop that goes like this, with each of these a function on their own:

check_events()
update_player_position()
collision_check()
draw_all()

Rather than have everything mushed together in the same area.

Upvotes: 1

Related Questions