gpt4 book ai didi

python - Pygame 碰撞仅作用于一个对象

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

我在 pygame 上编写一个平台游戏,我遇到了一个问题,我的平台只有一个碰撞被检测到。

这是我计算机科学类(class)的期末考试。我试过使用群组碰撞,但这只适用于 Sprite ,如果我想沿着这条路走下去,我必须重写我的很多代码。

# in main loop
for i in platforms:
if i.rect.colliderect(c) and c.isjump == False:
# If player is on platform and not jumping
c.falling = False
c.isjump = False
c.jumpcount = 10
c.onplat = True
else:
c.falling = True
c.onplat = False

这里的一切都正常(并且不会产生任何错误),除了我测试它时,只有一个平台阻止玩家掉落而其他平台只是通过玩家。如果需要,我可以展示更多代码。

最佳答案

如果您确定了一个“停止”播放器的平台,那么您必须打破循环:

for i in platforms: 
if i.rect.colliderect(c) and c.isjump == False:
c.falling = False
c.isjump = False
c.jumpcount = 10
c.onplat = True

break # <----- break the loop

else:
c.falling = True
c.onplat = False

否则,下一个平台的结果将覆盖该结果,列表中的最后一个平台无论如何都会设置结果。

请注意,您可以通过查找 any 来简化代码平台:

if c.isjump == False and any([i for i in platforms if i.rect.colliderect(c)]):
c.falling = False
c.jumpcount = 10
c.onplat = True

关于python - Pygame 碰撞仅作用于一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56329935/

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