Python动画,线从移动点开始并在第二个相交处停止

时间:2018-11-26 14:24:45

标签: python matplotlib simulation

我正在编写一个程序,以模拟从地球可见的火星的逆行运动。 这是地球和火星绕太阳旋转的平面图 从地球到火星还有一条直线。 但是,我需要它与火星相交,并继续前进直到与x = 15线相交

import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def _update_plot(i, fig, scat, l):
        scat.set_offsets(([math.cos(math.radians(i))*5, math.sin(math.radians(i))*5], [math.cos(math.radians(i/2))*10, math.sin(math.radians(i/2))*10], [0, 0]))
        l.set_data(([math.cos(math.radians(i))*5,math.cos(math.radians(i/2))*10],[math.sin(math.radians(i))*5,math.sin(math.radians(i/2))*10]))
        return [scat,l]

fig = plt.figure()

x = [0]
y = [0]

ax = fig.add_subplot(111)
ax.set_aspect('equal')
ax.grid(True, linestyle = '-', color = '0.10')
ax.set_xlim([-11, 11])
ax.set_ylim([-11, 11])

l, = plt.plot([],[], 'r--', zorder=1)
scat = plt.scatter(x, y, c = x, zorder=2)
scat.set_alpha(0.8)

anim = animation.FuncAnimation(fig, _update_plot, fargs = (fig, scat, l),
                               frames = 720, interval = 10)

plt.show()

1 个答案:

答案 0 :(得分:0)

我不确定我是否完全了解您想做什么,但是我假设您想将连接两个行星的线延长到x =15。在这种情况下,您可以执行以下操作:

  • 通过减去地球火星的位置并将其归一化来计算其方向。以其中一颗行星为起点。
  • 求解一阶方程,该方程为您提供到达x = 15轴所需的距离。
  • 检查结果是阳性还是阴性。如果它为正,那么继续前进;如果它为负,则我们选择了错误的行星,因为为了使直线连接两个平面,然后继续朝x = 15方向移动,我们需要取另一个行星。为此,我们需要反转方向并用新条件重新求解一阶方程。
  • 找到直线与x = 15轴相交的点的y坐标
  • 在x = 15轴上从行星到交点绘制一条线。

类似这样的事情应该可以解决:

def _update_plot(i, fig, scat, l):
        angle = math.radians(i)

        sun_pos = np.array([0., 0.])
        earth_pos = np.array([math.cos(angle)*5, math.sin(angle)*5])
        mars_pos = np.array([math.cos(angle / 2.) * 10, math.sin(angle / 2.) * 10])

        # compute the unit vector that points from Earth to Mars
        direction = mars_pos - earth_pos
        direction /= np.sqrt(np.dot(direction, direction))

        # find out where the line would intersect the x = 15 axis
        start_from = earth_pos
        alpha = (15 - start_from[0]) / direction[0]
        # if alpha comes out to be negative we picked the "wrong" planet
        if alpha < 0:
                start_from = mars_pos
                direction = -direction
                alpha = (15 - start_from[0]) / direction[0]
        y_line = start_from[1] + alpha * direction[1]

        # draw the planets
        scat.set_offsets((earth_pos, mars_pos, sun_pos))
        # draw the line
        l.set_data(([start_from[0], 15], [start_from[1], y_line]))
        return [scat,l]
相关问题