【发布时间】:2020-01-18 09:10:06
【问题描述】:
嗨,我是游戏开发新手,我正在使用 pygame,现在我遇到了这个问题,我有多个玩家必须同时躲避和杀死的敌人,但我的碰撞检测功能会检查一个敌人的碰撞一次。 除了列表中的第一个敌人外,该功能不适用于列表中的其他敌人。 这是创建敌人和碰撞检测的代码
class Enemy(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.width, self.height = 30, 30
self.vel = 10
self.color = (0, 0, 255)
self.rect = (x, y, self.width, self.height)
def create_enemies(n):
enemies = []
for i in range(n):
xcor = randint(0, (W - 50))
ycor = randint(0, H - H/2)
enemies.append(Enemy(xcor, ycor))
return enemies
n = 2
enemies = create_enemies(n)
def collision_detection(obj1, obj2list):
for obj2 in obj2list:
if (obj2.x < obj1.x < (obj2.x + obj2.width)) and (obj2.y < obj1.y < (obj2.y + obj2.height)):
return False
if (obj2.x < obj1.x < (obj2.x + obj2.width)) and (obj2.y < (obj1.y + obj1.height) < (obj2.y + obj2.height)):
return False
if (obj2.x < (obj1.x + obj1.width) < (obj2.x + obj2.width)) and (obj2.y < (obj1.y + obj1.height) < (obj2.y + obj2.height)):
return False
if (obj2.x < (obj1.x + obj1.width) < (obj2.x + obj2.width)) and (obj2.y < obj1.y < (obj2.y + obj2.height)):
return False
if obj1.x == obj2.x and obj1.y <= obj2.y + obj2.height:
return False
if obj1.x == obj2.x and obj1.y + obj1.height >= obj2.y:
return False
else:
return True
【问题讨论】:
-
代码格式的反引号是
`,而不是单引号'。 -
PyGame有pygame.Rect(),它具有检查冲突的方法,您不必编写它 - player.rect.colliderect(enemy.rect)。它还有Group,可用于检查碰撞将列出的敌人。
标签: python