我正在用 Python 做一个小型塔防项目,但在定位方面遇到了一些问题,我无法弄清楚。
所以我有一个塔的列表和一个四处移动的敌人的列表。
每次主游戏逻辑的 while 循环迭代时,我都有一个函数来检查每个生成的塔是否有目标。如果没有,我运行一个应该可以找到的函数。
for tw in tower_list:
tw.render(window)
if tw.target == None:
print(tw)
tw.target = find_target(tw)
print(tw.target)
这是在 find_target
函数中完成的。我正在 dispatch 正在寻找目标的塔。
def find_target(tw):
for e in enemy_list:
closest = 100000,100000
print("Checking distance for enemy", e)
dx = tw.x - e.x
dy = tw.y - e.y
if dy < 0:
dy *= -1
if dx < 0:
dx *= -1
if dx <= closest[0] and dy <= closest[1]:
closest = dx, dy
print("Closest one is ",e,"at distane",closest)
return e
我的模拟目前包括 3 个不同的敌人,我将它们分散开,以便每个塔都应该有不同的敌人作为目标。但它总是只检查并返回相同的敌人。
这可能是我忘记的一些愚蠢的事情,但我现在真的想不起来。
最佳答案
使用笛卡尔距离公式计算两点之间的距离。
它会让你始终有一个距离值,并保证每次都有较小的距离。 现在,如果一个敌人距离每座塔的 x 轴距离 1 以内,而所有其他敌人都在 x 轴距离 2 以内,那么即使他们可能更近,他们也永远不会被选中
编辑: 请使用上面的公式,因为您的计算不是距离函数 同样,在您的函数中,您第一次找到比更接近的值更小的值时返回 e 。 我会使其最接近的是一个包含敌人和距离的元组,因此您的代码应该是
def find_target(tw):
closest = (10000, None)
for e in enemy_list:
print("Checking distance for enemy", e)
dx = tw.x - e.x
dy = tw.y - e.y
distance = math.hypot(dx, dy)
if distance < closest[0]
closest[0] = distance
closest[1] = e
print("Closest one is ",closest[1],"at distane",closest[0])
return closest
关于python - Pygame 塔防游戏,寻找目标的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51327509/