gpt4 book ai didi

python - Sprite 碰撞和杀死 Sprite

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:58 26 4
gpt4 key购买 nike

我有两个 Sprite 组,ship_list 有 20 个飞船 Sprite ,all_sprites 有这 20 个 Sprite ,加上玩家 Sprite 。在主循环中,当检测到玩家与 ships_list 中的任何内容发生碰撞时,我了解到与玩家发生碰撞的船 Sprite 已从 ships_list 中删除。当我运行该程序时,所有 Sprite 都会出现,并且通过将玩家移动到船 Sprite 中它会消失。一切都很好,除了……我不明白为什么它们会消失。原因是虽然我知道碰撞后船只从 ships_list 中移除,但实际上每帧都重绘的是 all_sprites 列表,我没有明确说明在任何时候都从中删除了任何东西,那么碰撞是否也从 all_sprites 中删除了船 Sprite ?

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()

Find sprites in a group that intersect another sprite.

spritecollide(sprite, group, dokill, collided = None) -> Sprite_list

Return a list containing all Sprites in a Group that intersect with another Sprite. Intersection is determined by comparing the Sprite.rect attribute of each Sprite.

The dokill argument is a bool. If set to True, all Sprites that collide will be removed from the Group. (It doesn't mention it removing it from any other group..)

最佳答案

如果您查看打印 sprite 时显示的内容,您会发现它显示了该 sprite 存在的组数。

Sprite 有一个名为kill 的方法:

remove the Sprite from all Groups

kill() -> None

The Sprite is removed from all the Groups that contain it. This won’t change anything about the state of the Sprite. It is possible to continue to use the Sprite after this method has been called, including adding it to Groups.

看起来 sprite_collide 所做的,如果发生碰撞,它只是在 Sprite 上调用 kill()

关于python - Sprite 碰撞和杀死 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com