簡體   English   中英

如何驗證同一個 pygame.sprite.Group() 中的兩個精靈之間的碰撞?

[英]How to verify collision between two sprites in the same pygame.sprite.Group()?

我一直在嘗試為我的自上而下的 pygame 2d 游戲創建一個敵人移動系統。 但我的兩個敵人總是以互相超越而告終。 這就是為什么我決定創建一種方法來阻止敵人相互重疊,但我不知道如何檢查組中的敵人與組中的 rest 之間的碰撞,因為當我這樣做時,敵人一直以為他撞到了另一個敵人,但他只是撞到了自己。 有沒有簡單的方法來解決這個問題? 有關更多說明,請參閱下面代碼中的注釋

enemies = self.enemies.sprites()
for enemy in enemies:
    if pygame.sprite.spritecollide(enemy,self.enemies,False,pygame.sprite.collide_mask): # This is the part I would like to change because the enemy is always saying it is colliding with himself but I want him to see if he is in collision with the other enemies not himself even though he is part of that group
        print('collision')

您的一種選擇是 2 個嵌套循環::

enemies = self.enemies.sprites()
for i, enemy1 in enumerate(enemies):
    for enemy2 in enemies[i+1:]:
        if pygame.sprite.collide_mask(enemy1, enemy2):
            print('collision')

外循環遍歷所有敵人。 內部循環從第i+1個敵人迭代到最后。 這意味着每 2 個敵人之間的碰撞只測試一次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM