代码如下:
close all;
clear;
r_sun = 10;
r_earth = 5;
r_moon = 2;
angularVel_earth = 0.1; % rad/s
angularVel_moon = 0.5;
d_earth_sun = r_sun + r_earth + 60; % distance between sun center and earth center
d_earth_moon = r_earth + r_moon + 20;
figure(1);
hold on;
grid off;
rangemax = 300;
axis([-rangemax/2, rangemax/2, -rangemax/2, rangemax/2]);
axis square;
h_sun = fill(NaN, NaN, 'r', 'FaceAlpha', 1, 'EdgeColor', 'k', 'LineWidth', 0.5);
h_earth = fill(NaN, NaN, 'b', 'FaceAlpha', 0.5, 'EdgeColor', 'k', 'LineWidth', 0.5);
h_moon = fill(NaN, NaN, 'y', 'FaceAlpha', 1, 'EdgeColor', 'k', 'LineWidth', 0.5);
h_text_sun = text(r_sun + 2, 0, 'sun', 'FontSize', 7, 'HorizontalAlignment', 'left');
h_text_earth = text(0, 0, 'earth', 'FontSize', 7, 'HorizontalAlignment', 'left');
h_text_moon = text(0, 0, 'moon', 'FontSize', 7, 'HorizontalAlignment', 'left');
alpha = linspace(0, 2*pi, 100);
x_sun = r_sun * cos(alpha);
y_sun = r_sun * sin(alpha);
set(h_sun, 'XData', x_sun, 'YData', y_sun);
t = linspace(0, 63, 120);
pic_num = 1;
for i = 1:1:length(t)
angular_earth = t(i) * angularVel_earth; % earth angular pos relative to sun
angular_moon = t(i) * angularVel_moon; % moon angular pos relative to earth
x_earthCenter = d_earth_sun * cos(angular_earth);
y_earthCenter = d_earth_sun * sin(angular_earth);
x_earth = r_earth * cos(alpha) + x_earthCenter;
y_earth = r_earth * sin(alpha) + y_earthCenter;
x_moonCenter = x_earthCenter + d_earth_moon * cos(angular_moon);
y_moonCenter = y_earthCenter + d_earth_moon * sin(angular_moon);
x_moon = r_moon * cos(alpha) + x_moonCenter;
y_moon = r_moon * sin(alpha) + y_moonCenter;
set(h_earth, 'XData', x_earth, 'YData', y_earth);
set(h_moon, 'XData', x_moon, 'YData', y_moon);
set(h_text_earth, 'Position', [x_earthCenter + r_earth + 2, y_earthCenter, 0]);
set(h_text_moon, 'Position', [x_moonCenter + r_moon + 2, y_moonCenter, 0]);
drawnow;
pause(0.1);
% 将动画保存成gif图片
F = getframe(gcf);
I = frame2im(F);
[I,map] = rgb2ind(I,256);
if pic_num == 1
imwrite(I,map,'matlab动画-SunEarthMoon.gif','gif','Loopcount',inf,'DelayTime',0.1);
else
imwrite(I,map,'matlab动画-SunEarthMoon.gif','gif','WriteMode','append','DelayTime',0.1);
end
pic_num = pic_num + 1;
end
效果如下:
这份代码参考了几篇网上的文章,但是已经忘记了来源地址,此处就不注明参考的文章了...
代码块的语言选择里竟然没有matlab...?