0

为了让圆进入轨道,我得到了这个方程。我创建了一个无限循环,假设它应该永远在轨道上运行。x = cx + r*cos(t)y = cy + r*sin(t)

难道我做错了什么?

from graphics import *
import math
def main():
    win=GraphWin("Cirlce",600,600)
    x=250
    y=70
    c=Circle(Point(x,y),18)
    c.draw(win)
    v=True
    while v==True:
        c.undraw()
        x = x + c.getRadius()*math.cos(2)
        y = y + c.getRadius()*math.sin(2)
        c=Circle(Point(x,y),18)
        c.draw(win)
main()
4

2 回答 2

0

问题在这里:

    x = x + c.getRadius()*math.cos(2)
    y = y + c.getRadius()*math.sin(2)

你在一条直线上移动。而且,由于您的代码运行得非常快,它可能很快就会超出范围。正确的版本是:

x0, y0 = 0, 0 # Coordinates of the centre
r = 2         # Radius
t = 0
dt = 0.01     # Or anything that looks smooth enough.

while True:   # No need for an extra variable here
    c.undraw()    # I don't know this graphics library
                  # I will assume what you did is correct
    x = x0 + r * math.cos(t)
    y = y0 + r * math.sin(t)
    c=Circle(Point(x,y),18)
    c.draw(win)
    t += dt
    time.sleep(0.01)

在循环结束时,我让它进入睡眠状态,让它以有限的速度运行。一些图形库包含一个rate函数,允许您以每秒固定的帧数运行它,而与机器中循环的速度无关。

于 2014-03-27T19:06:06.017 回答
0

c.undraw() # 我不知道这个图形库,我会假设你所做的是正确的

当 GraphicsObjects 可以时,在每次循环迭代中使用c.undraw(),c = Circle(...)和似乎很浪费。但是,棘手的部分是运动是相对的,因此您必须计算与下一个位置的差异:c.draw()move(dx, dy)

import math
import time
from graphics import *

WINDOW_WIDTH, WINDOW_HEIGHT = 600, 600

win = GraphWin("Circle", WINDOW_WIDTH, WINDOW_HEIGHT)
win.setCoords(-WINDOW_WIDTH / 2, -WINDOW_HEIGHT / 2, WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)

ORBIT_RADIUS = 200
PLANET_RADIUS = 18
SOLAR_RADIUS = 48

x0, y0 = 0, 0  # Coordinates of the center

t = 0.0
dt = 0.01  # Or anything that looks smooth enough.
delay = 0.01

star = Circle(Point(x0, y0), SOLAR_RADIUS)
star.setFill("yellow")
star.draw(win)

orbit = Circle(Point(x0, y0), ORBIT_RADIUS)
orbit.setOutline("lightgray")
orbit.draw(win)

planet = Circle(Point(x0 + ORBIT_RADIUS * math.cos(t), y0 + ORBIT_RADIUS * math.sin(t)), PLANET_RADIUS)
planet.setFill("blue")
planet.draw(win)

while True:
    x, y = x0 + ORBIT_RADIUS * math.cos(t), y0 + ORBIT_RADIUS * math.sin(t)
    center = planet.getCenter()
    planet.move(x - center.getX(), y - center.getY())

    t = (t + dt) % (2 * math.pi)

    if win.checkMouse() is not None:
        break

    time.sleep(delay)

win.close()

我添加了一颗星,因为如果没有看到正在运行的东西,就很难意识到有东西在运行:

在此处输入图像描述

您可以单击窗口干净地退出。

于 2017-01-09T23:38:19.883 回答