玩家在pygame中发生玩家冲突

时间:2019-12-24 04:56:19

标签: python pygame

我正在尝试在RPG战斗地图上的4个可控角色之间创建碰撞检测。这是我正在使用的功能

def player_collission(Lord_x,Lord_y,Journeyman_x,Journeyman_y,Archer_x,Archer_y,
                  Cleric_x,Cleric_y):
print("Running")
if abs(Lord_x - Journeyman_x) <= 0 and abs(Lord_y - Journeyman_y) <= 0:
    print("Colission detected")
    return True
elif abs(Lord_x - Archer_x) <= 0 and abs(Lord_y - Archer_y) <= 0:
    print("Colission detected")
    return True
elif abs(Lord_x - Cleric_x) <= 0 and abs(Lord_y == Cleric_y) <= 0:
    print("Colission detected")
    return True
elif abs(Journeyman_x - Archer_x) <= 0 and abs(Journeyman_y - Archer_y) <= 0:
    print("Colission detected")
    return True
elif abs(Journeyman_x - Cleric_x) <= 0 and abs(Journeyman_y - Cleric_y) <= 0:
    print("Colission detected")
    return True
elif abs(Archer_x - Cleric_x) <= 0 and abs(Archer_y == Cleric_y) <= 0:
    print("Colission detected")
    return True
else:
    return False #I didnt use classes so it has alot of if statements


if player_up:
    p_collide = player_collission(Lord_x,Lord_y,Journeyman_x,Journeyman_y,Archer_x,Archer_y,
                  Cleric_x,Cleric_y)
    if current_player == "lord":
        if p_collide != True:
            Lord_y -= tile_increment
        if Lord_y <= 0:
            Lord_y = 50

发生的情况是,角色仍然相互移动,但是在已经相互移动并冻结所有运动之后,它会检测到碰撞。我不确定如何重新安排它以使其正常工作。

1 个答案:

答案 0 :(得分:0)

当碰撞已经发生时,您将对其进行检测。这就是为什么您看到字符重叠的原因。

相反,您应该检测是否将要发生碰撞,以防止可能导致碰撞的运动。

一个例子:

def move(coords, velocity):
  """Moves coords according to velocity."""
  x, y = coords  # Unpack a 2-tuple.
  vx, vy = velocity
  return (x + vx, y + vy)

tom_coords = (0, 0)  # Tom is in the corner.  
tom_v = (1, 1)  # Tom moves by diagonal.

jerry_coords = (5, 0)  # Jerry is a bit away from Tom.
jerry_v = (0, 1)  # Jerry moves vertically.

while True: 
  new_tom_coords = move(tom_coords, tom_v)  # Tom moves without fear.
  new_jerry_coords = move(jerry_coords, jerry_v)
  if new_jerry_coords == new_tom_coords:  # Would be a collision!
    new_jerry_coords = jerry_coords  # Back to previous tile.
    vx, vy = jerry_v
    jerry_v = (-vx, -vy)  # Jerry runs back.
    print("Collision imminent, Jerry runs away!")
  else:
    jerry_coords = new_jerry_coords  # Only update if no collision.
  # Could also check collisions with walls, etc.
  tom_coords = new_tom_coords
  # Not inside pygame, so just print it and wait for a key press.
  print('Tom:', tom_coords, 'Jerry:', jerry_coords)
  input("Enter to continue, Ctrl+C to stop ")

运行它,看看汤姆和杰里如何彼此靠近,却从未占据同一个瓷砖。