python - 如何使从 map 边缘生成的对象沿着对角线向中间移动?

标签 python pygame

我一直试图让我的对象沿着对角线向中间移动,而没有太多的滞后。我只能为该对象创建一条稳健的路径,仅进行向右、向左、向上或向下的移动。

运行时:

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/

相关文章:

python - 如何使用Python将RGB565字节数组转换为RGB888字节数组?

python - 强制 QWidget 占据 QScrollArea 中的所有可用高度

python - 如何在一段时间后停止Python程序

python - PyGame 局部变量

python - Pygame 一段时间后无法从资源中读取

python - Travis CI 将 ü 编码为 ¼

python - 从 pandas 列中删除依赖于另一列的字符串

python - pygame声音无法打开文件

python - Pygame图形错误: Couldn't open blue. png

python - python 密码强度检查器