【发布时间】:2014-04-03 16:07:34
【问题描述】:
我有两个精灵组,ship_list 有 20 个船精灵,all_sprites 有这 20 个精灵,加上玩家精灵。在主循环中,当检测到玩家与ships_list 中的任何东西之间发生碰撞时,我知道与玩家碰撞的船精灵已从ships_list 中删除。当我运行程序时,所有的精灵都会出现,并且通过将玩家移动到船精灵中,它就会消失。一切都很好,除了……我不明白他们为什么消失了。原因是虽然我知道在碰撞后船只从ships_list 中移除,但实际上每帧都在重绘all_sprites 列表,而且我在任何时候都没有明确地从中移除任何东西,所以是如果碰撞也从all_sprites 中删除了船精灵?
ship_list = pygame.sprite.Group() # just ship sprites
all_sprites = pygame.sprite.Group() # ship sprites + player sprite
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT or score == 20:
done = True
screen.fill(BLACK)
pos = pygame.mouse.get_pos()
player.rect.x = pos[0]
player.rect.y = pos[1]
**# is this line removing sprites from all_sprites??**
ships_hit_list = pygame.sprite.spritecollide(player, ship_list, True) # detect collisions
for ship in ships_hit_list:
score += 1
print score
all_sprites.draw(screen) # seems to lose sprites when ships_list does..
ship_list.update() # updating the position
pygame.display.flip()
clock.tick(24)
# properly quit
pygame.quit()
来自https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide
pygame.sprite.spritecollide()在一个组中查找与另一个精灵相交的精灵。
spritecollide(sprite, group, dokill, collided = None) -> Sprite_list返回一个列表,其中包含一个 Group 中所有与之相交的 Sprite 另一个雪碧。交点是通过比较确定的 每个 Sprite 的 Sprite.rect 属性。
dokill 参数是一个布尔值。如果设置为 True,所有 Sprite 碰撞将从组中删除。(它没有提到将其从任何其他组中删除..)
【问题讨论】:
标签: python python-2.7 python-3.x pygame