首页 > 解决方案 > 玩家在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

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

标签: pythonpygame

解决方案


当碰撞已经发生时,您就可以检测到它。这就是您看到字符重叠的原因。

相反,您应该检测是否会发生碰撞,并阻止可能导致碰撞的运动。

一个例子:

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 ")

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


推荐阅读