用matlab实现“太阳-地球-月亮运行示意图”动画

代码如下:

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...?

  • 15
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值