【发布时间】:2021-04-20 17:37:57
【问题描述】:
我正在努力做到这一点,当敌人与玩家发生碰撞时,会失去一条生命,并且玩家会被定位在屏幕的中心。它在大约一半的时间里有效,但在另一半的时间里,一次碰撞会失去两三个人的生命。
def collide(self):
for enemy in enemies:
if ((robot.hitbox[0] < enemy.x + 16 < robot.hitbox[0] + robot.hitbox[2]) or (robot.hitbox[0] < enemy.x - 16 < robot.hitbox[0] + robot.hitbox[2])) and ((robot.hitbox[1] < enemy.y + 16 < robot.hitbox[1] + robot.hitbox[3]) or (robot.hitbox[1] < enemy.y - 16 < robot.hitbox[1] + robot.hitbox[3])):
robot.alive = False
robot.x = 400
robot.y = 300
for enemy in enemies:
enemies.remove(enemy)
robot.lives -= 1
robot.alive = True
这是 Enemy 类下的一个函数,在 Enemy 的 draw 函数内部调用,在 while 循环中调用。
while running:
## add if robot.alive == True into loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
userInput = pygame.key.get_pressed()
if len(enemies) <= 3:
randSpawnX = random.randint(32, 768)
randSpawnY = random.randint(77, 568)
if (robot.x - 100 <= randSpawnX <= robot.x + 100) or (robot.y - 100 <= randSpawnY <= robot.y + 100):
randSpawnX = random.randint(32, 768)
randSpawnY = random.randint(77, 568)
else:
enemy = Enemy(randSpawnX, randSpawnY)
enemies.append(enemy)
if robot.alive == True:
for enemy in enemies:
enemy.move()
robot.shoot()
robot.movePlayer(userInput)
drawGame()
谁能帮我弄清楚为什么会发生这种情况?我相信这是因为记录了多次碰撞,但是由于我在记录第一次命中并且在失去生命之前将机器人移动到屏幕中间,为什么会发生这种情况?
【问题讨论】:
-
这看起来像是debouncing 的某个品牌,您想设置一个可能发生更多损坏的时间窗口。
-
@ti7 一定是因为使用 pygame.Rect.colliderect 没有解决。我将如何实施呢?线程?