我一直试图让我的对象沿着对角线向中间移动,而没有太多的滞后。我只能为该对象创建一条稳健的路径,仅进行向右、向左、向上或向下的移动。
运行时:
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)
最佳答案
您必须找到 Unit vector从 (ex
, ey
) 到 (宽度//2
, 高度//2
)。
单位向量可以通过将(ex
, ey
)向量除以(width//2
,height//2
) 按其长度。
向量的长度可以通过Euclidean distance来计算.
最后将向量乘以不大于点之间距离的比例(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)
关于python - 如何使从 map 边缘生成的对象沿着对角线向中间移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59726059/