【问题标题】:Get Python turtle to face in direction of line being plotted让 Python 乌龟朝向正在绘制的线的方向
【发布时间】:2019-07-25 07:27:47
【问题描述】:

我试图让乌龟形状跟随一条线的方向。

我有一个简单的抛物线,我希望乌龟形状跟随直线的方向 - 当图形上升时,乌龟面朝上,当图形下降时,乌龟面朝下。
我使用goto() 作为海龟的位置,x=x+1 作为图表上的 x 位置:

t.goto(x,y)
t.right(??) - this?
t.left(??) - this?
t.setheading(??) or this?

实现这一目标的最佳方法是什么?当我尝试在 while 循环中使用 t.right() 时(我一直在循环直到 x 完成),海龟在移动时继续旋转一圈,这 不是 我想要的。


仍然没有得到这个。我添加了建议的额外代码 - 这是我想要实现的编辑和完整代码......

我正在使用轨迹的物理公式(我使用了这个,所以我知道我输出的值是正确的)。 http://www.softschools.com/formulas/physics/trajectory_formula/162/

import math
import turtle
import time
w=turtle.Turtle()


i=0
angle=66.4
velocity=45.0
g=9.8

t=math.tan(math.radians(angle))
c=math.cos(math.radians(angle))

turtle.delay(9)

w.shape("turtle")
w.setheading(90)

while i < 150:
    start = i * t
    middle = g*(i**2)
    bottom =(2*(velocity**2)*c**2)
    total = start-middle/bottom
    print(total)

    w.setheading(turtle.towards(i,total))
    w.goto(i,total)

    i=i+1

turtle.exitonclick()

【问题讨论】:

  • 你能看看我为这个问题编辑的代码吗?

标签: python graphics turtle-graphics


【解决方案1】:

我同意@NicoSchertler 的观点,即导数的反正切是数学上的方法。但如果只是为了获得良好的视觉效果,还有一种更简单的方法。我们可以结合 turtle 的 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()

【讨论】:

    【解决方案2】:

    海龟的方向可以根据你的函数在当前位置的导数来确定。

    如果你有这个函数作为一个 sympy 函数,你可以让 Python 来做微分。或者你可以自己做。如果你的功能是

    y = x^2
    

    ,则导数为

    dy = 2 * x
    

    给定在当前位置的导数,它的反正切给你海龟的航向:

    t.setheading(math.atan(dy))
    

    确保海龟的角度模式设置为弧度或将其转换为度数

    t.setheading(math.degrees(math.atan(dy)))
    

    【讨论】:

    • 谢谢。我仍在试图理解,如果我输入一个数字,例如 t.right(90),它会在穿过抛物线时继续旋转。
    • 因为t.right(90) 的意思是:从当前方向右转90°。并且多次右转最终会形成一个圆圈。
    最近更新 更多