首页 > 解决方案 > 设置python海龟的朝向线的方向

问题描述

我使用 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)

输出

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

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

谢谢!

标签: pythonpython-3.xturtle-graphicspython-turtle

解决方案


除了三角函数,你可以简单地使用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()

在此处输入图像描述


推荐阅读