用 VS 写一段行星运行轨迹代码
时间: 2024-01-27 21:02:58 浏览: 116
以下是使用 C# 和 Windows Forms 库实现的行星运行轨迹代码示例,可以在 Visual Studio 中编写和运行:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public class PlanetMotion : Form
{
// 行星的半径
private float radius = 100.0f;
// 行星的公转周期
private float period = 5.0f;
// 行星的初始角度
private float initialAngle = 0.0f;
// 行星的轨道倾角
private float inclination = (float)Math.PI / 6.0f;
// 行星的自转角速度
private float rotationSpeed = (float)Math.PI / 2.0f;
// 行星的轨道速度
private float velocity;
// 行星的当前角度
private float angle;
public PlanetMotion()
{
// 设置窗口标题和大小
Text = "Planet Motion";
Size = new Size(600, 600);
// 计算轨道速度
velocity = 2.0f * (float)Math.PI / period;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
// 绘制太阳和行星
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Pen sunPen = new Pen(Color.Yellow, 10.0f);
g.DrawEllipse(sunPen, ClientSize.Width / 2 - 50, ClientSize.Height / 2 - 50, 100, 100);
Pen planetPen = new Pen(Color.Blue, 5.0f);
float x = ClientSize.Width / 2 + radius * (float)Math.Cos(angle);
float y = ClientSize.Height / 2 + radius * (float)Math.Sin(angle) * (float)Math.Cos(inclination);
g.DrawEllipse(planetPen, x - 10, y - 10, 20, 20);
// 让行星自转
Matrix matrix = new Matrix();
matrix.Translate(x, y);
matrix.Rotate(rotationSpeed * angle * 180.0f / (float)Math.PI);
g.Transform = matrix;
g.DrawEllipse(planetPen, -5, -5, 10, 10);
// 重绘窗口
Invalidate();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// 启动定时器
Timer timer = new Timer();
timer.Interval = 20;
timer.Tick += new EventHandler(OnTimer);
timer.Start();
}
private void OnTimer(Object sender, EventArgs e)
{
// 计算行星的新位置
angle += velocity * 0.02f;
if (angle > 2.0f * (float)Math.PI) angle -= 2.0f * (float)Math.PI;
// 重绘窗口
Invalidate();
}
static void Main()
{
Application.Run(new PlanetMotion());
}
}
```
这段代码实现了一个简单的行星绕太阳公转的动画效果,使用了 Windows Forms 库中的 Form 类和 Graphics 类。在 Main 方法中创建一个 PlanetMotion 对象并运行,即可打开窗口预览行星的运动轨迹。
阅读全文
相关推荐

















