Pygame 如何找到数组中最近的精灵并锁定它?
Pygame how to find the nearest sprite in an array and lock onto it?
我有一个导弹精灵,如果我射击它。它应该去最近的敌方精灵。我不知道如何继续下去。我完全知道我们将使用一些距离公式,但这不是问题所在。问题是循环遍历列表中的敌人并找到离导弹最近的敌人。
我已经尝试过使用 for 循环,但这是我目前所能想到的。我看过其他帖子,但 none 也有相同类型的问题。仅适用于尚未在列表中的单个精灵。
导弹class
class Missile:
missile = pygame.image.load("Missile-1.png")
def __init__(self,x,y):
self.x = x
self.y = y
self.yvel = 15
self.xvel = 5
def draw(self,win):
win.blit(missile,(self.x,self.y))
def chase(self):
for enemy in enemies:
#some code
数组:
missiles = []
enemies = []
我预计导弹会飞向最近的敌人。
我建议使用 2 点之间的 pygame.math.Vector2
and the function .distance_to()
to calculate the Euclidean distance 距离。
def chase(self):
pos = pygame.math.Vector2(self.x, self.y)
enemy = min([e for e in enemies], key=lambda e: pos.distance_to(pygame.math.Vector2(e.x, e.y)))
解释:
lambda e: pos.distance_to(pygame.math.Vector2(e.x, e.y))
计算参数 e
到 pygame.math.Vector2
对象的距离 pos
.
min
finds the minimum element in an iterable。 "minimum" 值由设置为 key
参数的函数给出。
pos
由Missile
的位置初始化。对于 enemies
的每个元素,计算到 pos
的距离,并且最接近 pos
的敌人由 min
返回。
当然这可以通过手动计算平方欧氏距离进一步简化:
def chase(self):
enemy = min([e for e in enemies], key=lambda e: pow(e.x-self.x, 2) + pow(e.y-self.y, 2))
我有一个导弹精灵,如果我射击它。它应该去最近的敌方精灵。我不知道如何继续下去。我完全知道我们将使用一些距离公式,但这不是问题所在。问题是循环遍历列表中的敌人并找到离导弹最近的敌人。
我已经尝试过使用 for 循环,但这是我目前所能想到的。我看过其他帖子,但 none 也有相同类型的问题。仅适用于尚未在列表中的单个精灵。
导弹class
class Missile:
missile = pygame.image.load("Missile-1.png")
def __init__(self,x,y):
self.x = x
self.y = y
self.yvel = 15
self.xvel = 5
def draw(self,win):
win.blit(missile,(self.x,self.y))
def chase(self):
for enemy in enemies:
#some code
数组:
missiles = []
enemies = []
我预计导弹会飞向最近的敌人。
我建议使用 2 点之间的 pygame.math.Vector2
and the function .distance_to()
to calculate the Euclidean distance 距离。
def chase(self):
pos = pygame.math.Vector2(self.x, self.y)
enemy = min([e for e in enemies], key=lambda e: pos.distance_to(pygame.math.Vector2(e.x, e.y)))
解释:
lambda e: pos.distance_to(pygame.math.Vector2(e.x, e.y))
计算参数 e
到 pygame.math.Vector2
对象的距离 pos
.
min
finds the minimum element in an iterable。 "minimum" 值由设置为 key
参数的函数给出。
pos
由Missile
的位置初始化。对于 enemies
的每个元素,计算到 pos
的距离,并且最接近 pos
的敌人由 min
返回。
当然这可以通过手动计算平方欧氏距离进一步简化:
def chase(self):
enemy = min([e for e in enemies], key=lambda e: pow(e.x-self.x, 2) + pow(e.y-self.y, 2))