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
发生的情况是角色仍然相互移动,但它在已经相互移动后检测到碰撞并冻结所有移动。我不确定如何重新安排它以使其正常工作。
解决方案
当碰撞已经发生时,您就可以检测到它。这就是您看到字符重叠的原因。
相反,您应该检测是否会发生碰撞,并阻止可能导致碰撞的运动。
一个例子:
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 ")
运行它,看看汤姆和杰瑞如何彼此靠近,但从不占据同一个瓷砖。
推荐阅读
- vsto - 在 Word VSTO 中创建自己的自定义 RibbonControl 类型
- python - 使用朴素贝叶斯训练模型
- mysql - Sql将值从一列移动到两个不同的列
- c# - 没有 CheckNetIsolation.exe LoopbackExempt 的 UWP C# .Net 套接字服务器
- state - AgGrid 检测列/过滤器/排序事件的变化
- javascript - 从另一个组件更改自定义组件的 css 类
- foreach - SwiftUI:删除列表的最后一项并切换到另一个选项卡视图后出现“致命错误:索引超出范围”
- javascript - 将 botkit 框架部署到 azure 并在网络聊天中进行测试返回 502
- replaykit - 将 ReplayKit 与 MacCatalyst 一起使用
- android - 我如何将多个数据添加到 firebase 实时数据库上的同一个令牌