我正试图让乌龟的形状跟随一条线的方向。
我有一个简单的抛物线,我希望乌龟形状遵循线的方向 - 当图形上升时,乌龟……
我同意@NicoSchertler的观点,即导数的反正切是数学方法。但如果仅仅是为了获得良好的视觉效果,那么就会有更简单的方法。我们可以结合龟的 setheading() 和 towards() 方法,在我们去那儿之前不断设置龟朝向下一个位置:
setheading()
towards()
from turtle import Screen, Turtle turtle = Turtle(shape='turtle', visible=False) turtle.penup() turtle.goto(-20, -400) turtle.pendown() turtle.setheading(90) turtle.showturtle() for x in range(-20, 20): y = -x ** 2 turtle.setheading(turtle.towards(x, y)) turtle.goto(x, y) screen = Screen() screen.exitonclick()
乌龟的方向可以从你当前位置的函数导数确定。
如果您具有作为sympy函数的功能,您可以要求Python进行区分。或者你可以自己做。如果你的功能是
y = x^2
那么衍生物就是
dy = 2 * x
鉴于当前位置的导数,其反正切线为您提供了乌龟的标题:
t.setheading(math.atan(dy))
确保乌龟的角度模式设置为弧度或将其转换为度数
t.setheading(math.degrees(math.atan(dy)))