python在graphics.py中移动一个圆绕另一个圆



我正在使用graphics.py库编写Python程序。我想画两个圆,然后让其中一个绕着另一个循环。我知道我必须使用sin和cos函数,但我不知道它的数学公式是什么。

这是我的代码:

from graphics import *
from math import sin, cos, pi
from time import sleep
win = GraphWin('Program', 500, 500)
win.setBackground('white')
c = Circle(Point(250, 250), 50)
c.draw(win)
c1 = Circle(Point(250, 175), 25)
c1.draw(win)
while True:
c1.move() #there I have to use some formula for moving circle c1 around circle c
sleep(1)
win.getMouse()
win.close()

必须使用一点数学。根据您的示例,您希望圆圈彼此相邻。

因此,它们中心之间的距离总是r1+r2。这是向量的长度。我们需要把这个向量分成x轴和y轴两个部分。这就是正弦和余弦函数的作用,它在给定角度的值意味着我们需要沿着轴移动多远的中心。

计算完新位置后,我们要做的就是从当前位置减去新位置,看看我们需要移动另一个圆多远。

from graphics import *
from math import sin, cos, pi
from time import sleep
win = GraphWin('Program', 500, 500)
win.setBackground('white')
c_origin_x = 250
c_origin_y = 250
c_radius = 50
c = Circle(Point(c_origin_x, c_origin_y), c_radius)
c.draw(win)
c1_oldpos_x = c_origin_x # doesn't actually matter, it gets moved immediately
c1_oldpos_y = c_origin_y
c1_radius = 25
c1 = Circle(Point(c1_oldpos_x, c1_oldpos_y), c1_radius)
c1.draw(win)
angle = 0 # initial angle
while True:
c1_newpos_x = sin(angle) * (c_radius + c1_radius) + c_origin_x
c1_newpos_y = cos(angle) * (c_radius + c1_radius) + c_origin_y
c1.move(c1_newpos_x - c1_oldpos_x, c1_newpos_y - c1_oldpos_y)
sleep(1)
angle += 0.1 * pi # this is what will make a position different in each iteration
c1_oldpos_x = c1_newpos_x
c1_oldpos_y = c1_newpos_y

win.getMouse()
win.close()

最新更新