如何编写算法来计算同一组中两个精灵的碰撞?



我正在制作一个包含敌人和玩家的小游戏。在某些时候,玩家可以射击敌人,敌人可以用自己的射击来回应。有些关卡包含不止一个敌人。因此,在某些情况下,如果玩家在敌人之间并设法摆脱困境,一个敌人可能会"意外"射击另一个敌人。在两个守卫都会开枪而玩家让开的情况下,我想消灭两个敌人的子弹。有没有办法做到这一点。

目前,我的武器课上有这种方法。

def selfannihilation(self, guardbulletsprites):
guardbulletsprites.remove(self)
selfannihilation = pygame.sprite.spritecollide(self, guardbulletsprites, True)
f not selfannihilation:
guardbulletsprites.add(self)
And i call this method within a seperate function, checking bullet conditions. collision with walls, enemies, player, player bullets
```py
for bullet in guardbulletsprites:
bullet.selfannihilation(guardbulletsprites)

在执行过程中,算法没有像我预期的那样工作。只删除了一颗子弹,可能是因为spritecollide行中的"True"。我希望从guardbulletsprites组中删除两个项目符号。

提前致谢

下面的代码是类武器中的一种方法

def self anhilation(self, guardbulletsprites(:

changed = False
temp = pygame.sprite.Group.copy(guardbulletsprites)
temp.remove(self)
selfannihilation = pygame.sprite.spritecollide(self, temp, True)
if not selfannihilation:
guardbulletsprites.add(self)
else:
changed = True
return changed, guardbulletsprites

在调用它的函数中,我写了。

def bulletanniation(guardbulletsprites(:

for bullet in guardbulletsprites:
change, guardbulletsprites = bullet.selfannihilation(guardbulletsprites)
if change:
bulletannihilation(guardbulletsprites)

if change: part 利用递归再次调用该函数,否则它将循环访问错误的次数,仅当 guardbulletsprites 的内容已更改时。

我使用了一个临时变量,其中包含与警卫子弹精灵几乎相同的内容,因为我觉得实际的警卫子弹精灵的内容被意外删除了。

老实说,我不知道这是如何工作的。

最新更新