检查pygame中sprites中的多个碰撞

问题描述:

我目前正在使用pygame,并且我想创建多个sprite并检查至少两个碰撞。我想出了两个while循环的想法,但最终变得非常复杂。还有其他方法可以尝试吗?检查pygame中sprites中的多个碰撞

+0

欢迎来到*。请阅读并遵守帮助文档中的发布准则。 [在主题](http://*.com/help/on-topic)和[如何提问](http://*.com/help/how-to-ask)适用于此处。 *不是一个设计,编码,研究或教程服务。 – Prune

+0

另请参见发布编码问题的具体细节:[最小,完整,可验证的示例](http://*.com/help/mcve)。在发布您的MCVE代码并准确描述问题之前,我们无法为您提供有效的帮助。 我们应该能够将发布的代码粘贴到文本文件中,并重现您描述的问题。 – Prune

+0

你的游戏是什么?只要处理你的对象的位置,并比较它们。如果它们是相同的点,则会出现碰撞。您也可以使用颜色来检查Unity中的碰撞情况。 – WaLinke

使用pygame.sprite.spritecollide可以获得与玩家碰撞的精灵列表,然后循环播放此列表以对碰撞的精灵进行操作。

还有groupcollide,您可以使用它来检测两个精灵组之间的冲突。它返回一个带有组1的精灵的字典作为键和组2的碰撞精灵作为值。

import sys 
import pygame as pg 
from pygame.math import Vector2 


class Player(pg.sprite.Sprite): 

    def __init__(self, pos, *groups): 
     super().__init__(*groups) 
     self.image = pg.Surface((120, 60)) 
     self.image.fill(pg.Color('dodgerblue')) 
     self.rect = self.image.get_rect(center=pos) 


class Enemy(pg.sprite.Sprite): 

    def __init__(self, pos, *groups): 
     super().__init__(*groups) 
     self.image = pg.Surface((120, 60)) 
     self.image.fill(pg.Color('sienna1')) 
     self.rect = self.image.get_rect(center=pos) 


def main(): 
    screen = pg.display.set_mode((640, 480)) 
    clock = pg.time.Clock() 
    all_sprites = pg.sprite.Group() 
    enemy_group = pg.sprite.Group(Enemy((200, 250)), Enemy((350, 250))) 
    all_sprites.add(enemy_group) 
    player = Player((100, 300), all_sprites) 

    done = False 

    while not done: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       done = True 
      elif event.type == pg.MOUSEMOTION: 
       player.rect.center = event.pos 

     all_sprites.update() 
     # Check which enemies collided with the player. 
     # spritecollide returns a list of the collided sprites. 
     collided_enemies = pg.sprite.spritecollide(player, enemy_group, False) 

     screen.fill((30, 30, 30)) 
     all_sprites.draw(screen) 
     for enemy in collided_enemies: 
      # Draw rects around the collided enemies. 
      pg.draw.rect(screen, (0, 190, 120), enemy.rect, 4) 

     pg.display.flip() 
     clock.tick(30) 


if __name__ == '__main__': 
    pg.init() 
    main() 
    pg.quit() 
    sys.exit() 
+0

非常感谢您的回复!这帮了很多!我是pygame的新手,有时需要编写代码。再次感谢。 –