我有两艘飞船和一套药丸,这些药片应该会从屏幕的顶部不断往下滴。当我的飞船与一颗药丸相撞时,药丸应该会消失,但它们不会消失。药丸会在离y=win峈高度50像素的地方消失。在
在运行了一些测试之后,我可以说药丸是由“碰撞精灵”检测到的,它们被从“pillGroup”组中移除,但是它们仍然被快速地传送到屏幕上并通过飞船。我要药片立刻消失。在
以下是我的算法的编辑版本:
pillGroup = pygame.sprite.Group()
# Gameplay
while play:
# Checks if window exit button pressed
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
# Keypresses
pill = Pill()
pill.add(pillGroup)
pillGroup.update()
pygame.sprite.spritecollide(ship_right, pillGroup, True)
# Print background
screen.fill(WHITE)
pillGroup.draw(screen)
这是游戏的完整版本。请注意,我增加了船的尺寸来填充屏幕。试着把飞船移到屏幕的顶部,你会看到药丸在到达屏幕底部时消失,而不是第一次接触到飞船时。在
^{pr2}$
问题是
pygame.sprite.spritecollide
检查作为第一个参数传递的精灵的rect
属性,并将其与精灵组中精灵的rect
属性进行比较。在但是,实际上并没有更改
Ship
实例的rect
属性。在去掉
x
和y
属性,只使用rect
属性来存储精灵的位置。在以下是更新版本:
注意移动代码是如何简化的。我还使用了
kill()
来删除屏幕外的药片,并使用了Rect
类的一些特性,比如设置初始位置、移动到位(move_ip
)以及确保Rect
不会离开特定区域(clamp_ip
)。在相关问题 更多 >
编程相关推荐