如何检测 Rect 列表和另一个 Rect 列表之间的冲突
How to detect collision between a list of Rect and another list of Rects
所以我正在 pygame 制作僵尸射击游戏。我有一个播放器 - 一个僵尸列表 - 和一个子弹列表。
都是长方形。
我需要检测所有子弹和所有僵尸之间的碰撞。 - 我尝试了 colliderect
但 collidelist
但那是在对象和列表之间。我想要一个列表和另一个列表。
当我尝试这样做时:
def collide(self):
for zombie in self.zombies:
index = self.zombie.collidelist(self.bullets)
if index:
print("hit")
在 zombie class 中它给出错误 TypeError: Argument must be a sequence of rectstyle objects.
没有函数可以直接测试 pygame 中 2 个矩形列表之间的冲突,除非您使用 pygame.sprite.Group
and pygame.sprite.groupcollide
. If you have 2 pygame.sprite.Group
对象(group1
和 group2
)您可以执行以下操作:
if pygame.sprite.groupcollide(group1, group2, True, True):
print("hit")
如果您必须在循环中列出 pygame.Rect
objects (rect_list1
and rect_list2
) you can use collidelist()
or collidelistall()
。例如:
for rect1 in rect_list1:
index = rect1.collidelist(rect_list2)
if index >= 0:
print("hit")
for rect1 in rect_list1:
collide_list = rect1.collidelistall(rect_list2)
if collide_list:
print("hit")
如果您没有 pygame.Rect
个对象,则需要创建它们并 运行 在嵌套循环中进行碰撞测试:
for zombie in self.zombies:
zombieRect = pygame.Rect(zombie.x, zombie.y, zombie.width, zombie.height)
for bullet in self.bullets:
bulletRect = pygame.Rect(bullet.x, bullet.y, bullet.width, bullet.height)
if zombieRect.colliderect(bulletRect):
print("hit")
所以我正在 pygame 制作僵尸射击游戏。我有一个播放器 - 一个僵尸列表 - 和一个子弹列表。 都是长方形。
我需要检测所有子弹和所有僵尸之间的碰撞。 - 我尝试了 colliderect
但 collidelist
但那是在对象和列表之间。我想要一个列表和另一个列表。
当我尝试这样做时:
def collide(self):
for zombie in self.zombies:
index = self.zombie.collidelist(self.bullets)
if index:
print("hit")
在 zombie class 中它给出错误 TypeError: Argument must be a sequence of rectstyle objects.
没有函数可以直接测试 pygame 中 2 个矩形列表之间的冲突,除非您使用 pygame.sprite.Group
and pygame.sprite.groupcollide
. If you have 2 pygame.sprite.Group
对象(group1
和 group2
)您可以执行以下操作:
if pygame.sprite.groupcollide(group1, group2, True, True):
print("hit")
如果您必须在循环中列出 pygame.Rect
objects (rect_list1
and rect_list2
) you can use collidelist()
or collidelistall()
。例如:
for rect1 in rect_list1:
index = rect1.collidelist(rect_list2)
if index >= 0:
print("hit")
for rect1 in rect_list1:
collide_list = rect1.collidelistall(rect_list2)
if collide_list:
print("hit")
如果您没有 pygame.Rect
个对象,则需要创建它们并 运行 在嵌套循环中进行碰撞测试:
for zombie in self.zombies:
zombieRect = pygame.Rect(zombie.x, zombie.y, zombie.width, zombie.height)
for bullet in self.bullets:
bulletRect = pygame.Rect(bullet.x, bullet.y, bullet.width, bullet.height)
if zombieRect.colliderect(bulletRect):
print("hit")