在 python 中创建曲率动画

Creating curvature animation in python

我现在已经面临一个问题 2 周了,但我仍然无法弄清楚从哪里开始。问题是关于创建一个关于两个点相互追逐的曲率动画。其中一个在 x 轴上沿直线移动,另一个从 x 轴向下开始(在 y 轴上,例如 p(0:-10)),根据追逐原理,第二个尝试在连续面对它的同时抓住第一个。我写了一些代码来帮助我获得实际答案,但我无法以非常宝贵的方式将其可视化。我使用 python 作为我的主要编码语言。

提前致谢 卢卡·K

好像是 enemy following player 上周被问到 tkinterpygame

你计算对象之间的向量

diff_x = player_x - enemy_x
diff_y = player_y - enemy_y

和距离

distance = (diff_x**2 + diff_y**2)**0.5  # Pythagoras: a**2 + b**2 = c**2

计算归一化向量(长度为1的向量)

normal_x = diff_x/distance
normal_y = diff_y/distance

你可以乘以 speed 来计算 move_xmove_yenemy

enemy_move_x = enemy_speed * normal_x
enemy_move_y = enemy_speed * normal_y

你可以用它来移动enemy和画线。


要绘制它,您可以使用不同的模块 - 任何 GUI 框架,如 tkinterPyQtwxPython 或 game/media 库,如 pygamepyglet。最终您可以生成可用于创建动画 GIF 的图像。


import tkinter as tk

def follow(player_x, player_y, enemy_x, enemy_y, enemy_speed=5):
    diff_x = player_x - enemy_x
    diff_y = player_y - enemy_y

    distance = (diff_x**2 + diff_y**2)**0.5  # Pythagoras: a**2 + b**2 = c**2

    if distance <= enemy_speed:
        return diff_x, diff_y

    normal_x = diff_x/distance
    normal_y = diff_y/distance

    enemy_move_x = enemy_speed * normal_x
    enemy_move_y = enemy_speed * normal_y

    return enemy_move_x, enemy_move_y

def update_game():
    global player_x
    global player_y
    global enemy_x
    global enemy_y

    # draw line for player
    canvas.create_line(player_x, player_y, player_x+player_move_x, player_y+player_move_y, fill='green')

    # move player
    player_x += player_move_x
    player_y += player_move_y
    canvas.move(player_id, player_move_x, player_move_y)

    # calculate move for enemy
    enemy_move_x, enemy_move_y = follow(player_x, player_y, enemy_x, enemy_y, enemy_speed)

    # draw line for enemy
    canvas.create_line(enemy_x, enemy_y, enemy_x+enemy_move_x, enemy_y+enemy_move_y, fill='red')

    # move enemy
    enemy_x += enemy_move_x
    enemy_y += enemy_move_y
    canvas.move(enemy_id, enemy_move_x, enemy_move_y)

    root.after(100, update_game) # repeate after 100ms (0.1s)

# --- main ---

# player start position and move ("speed")
player_x = 5
player_y = 50
player_move_x = 4
player_move_y = 0 # try for `1`

# enemy start position and speed
enemy_x = 5
enemy_y = 500
enemy_speed = 5

root = tk.Tk()

canvas = tk.Canvas(root, width=750, height=500)#, bg='gray')
canvas.pack()

player_id = canvas.create_oval(player_x-5, player_y-5, player_x+5, player_y+5, fill='green')
enemy_id = canvas.create_oval(enemy_x-5, enemy_y-5, enemy_x+5, enemy_y+5, fill='red')

update_game()

root.mainloop()

顺便说一句: 在回答问题 时你有相同的代码但是你必须使用键 WASD 移动播放器并且它不绘制线.