设置python海龟的航向为线的方向

Set python turtle's heading in the direction of the line

我使用 python turtle 模块制作了一条线。这是代码:

import turtle

t = turtle.Turtle()
def line(x1, y1, x2, y2):
    t.penup()
    t.setpos(x1, y1)
    t.pendown()
    t.setpos(x2, y2)

输出如下所示:(line(0, 0, 100, 100)

Output

乌龟的航向为 0.0。我需要将它设置在画线的方向,这样如果我这样做 t.fd(50) 它会继续画线。

我从用户那里得到了线的坐标,那么如何将海龟的航向与线对齐?

谢谢!

而不是三角函数,您可以简单地使用 turtle 的 towards() 方法结合 setheading() 在移动到目标之前指向目标:

from turtle import Screen, Turtle

def line(x1, y1, x2, y2):
    turtle.penup()
    turtle.setpos(x1, y1)
    turtle.pendown()

    turtle.setheading(turtle.towards(x2, y2))
    turtle.setpos(x2, y2)

screen = Screen()

turtle = Turtle()

line(0, 0, 100, 100)

screen.exitonclick()