如何使从地图边缘生成的对象沿着对角线朝中间延伸?



我一直在尝试让我的对象沿着对角线向中间移动,而不会有很多滞后。我只能为对象创建一个健壮的路径,只做右、左、上或下运动。

运行时:

pygame.draw.rect(screen,(0,0,0),(0,0,width,height))
hero()
ewaste()
if distance(ex,ey,(width//2),(height//2)) != 0: 
(dx,dy) = ((x - ex)/math.sqrt((x - ex) ** 2 + (y - ey) ** 2), (y - ey)/math.sqrt((x - ex) ** 2 + (y - ey) **2))
ex, ey = int(ex + dx * 10), int(ey + dy * 10)

你必须找到从(exey(到(width//2height//2(的单位向量。
单位向量可以通过将向量从(exey(除以(width//2height//2(的长度来找到。
向量的长度可以通过欧几里得距离计算。
最后将向量乘以不大于点之间距离的刻度(step(,并将其添加到位置。 例如:

# vector from (`ex`,  `ey`) to (`width//2`, `height//2`)
dx, dy = width//2 - ex, height//2 - ey
# [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance)
len = math.sqrt(dx*dx + dy*dy)
if len > 0:
# [Unit vector](https://en.wikipedia.org/wiki/Unit_vector)
ndx, ndy = dx/len, dy/len
# minimum of step size and distance to target
step = min(len, 10)
# step forward
ex, ey = round(ex + ndx * step, round(ey + ndy * step)

最新更新