C# Solar System,行星轨道数学问题

C# Solar System, trouble with planetary orbit math

我正在写一个太阳系模拟程序;我只是一个使用 C# 的初学者。

我在自定义控件上使用 OnPaint 在窗体上绘制图形。我在动画方面遇到问题,因为它不是让行星围绕太阳旋转(控件中心的固定点),而是围绕行星应该所在的点旋转。但是这个点还是绕着控件的中心旋转。

我已经在自定义控件的顶部声明了这些变量:

private color col1;
private float angle;
private double r1, r2, ex, why;

下面是OnPaint中的代码:

protected override void OnPaint(PaintEventArgs pe)
{
        this.DoubleBuffered = true;
        base.OnPaint(pe);
        Graphics g = pe.Graphics;

        AnimationControl anim = new AnimationControl(); 

        Planet sun = new Planet(50, 60);
        sun.drawSun(pe);

        angle += 0.01f;
        if (angle > 359)
        {
            angle = 0; 
        }
        Matrix matrix = new Matrix();
        matrix.Rotate(angle, MatrixOrder.Append);
        matrix.Translate(SandboxForm.ActiveForm.Width / 2,
            SandboxForm.ActiveForm.Height / 2, MatrixOrder.Append);
        g.Transform = matrix;

        r1 = 200; 
        r2 = 100; 
        double diameter = 40; 
        col1 = Color.Red;
        SolidBrush bru2 = new SolidBrush(col1); 
        ex = ((SandboxForm.ActiveForm.Width / 2) - diameter - (sun.getSunRadius())) + (r1 * (Math.Cos(angle))); /
        why = ((SandboxForm.ActiveForm.Height / 2) - diameter - (sun.getSunRadius())) + (r2 * (Math.Sin(angle))); 
        g.FillEllipse(bru2, (float)ex, (float)why, (float)diameter, (float)diameter); 
        Invalidate();
}

我不得不简化你的代码,因为缺少 类 等。但是在这你可以看到它现在做你想要的。

如果您尝试此代码,您会发现旋转和平移的顺序很重要,但当您尝试我的建议时它没有任何效果,因为您在应用变换之前进行绘画。

另请注意,我的矩阵周围有 using,那是因为您应该在用完它后将其丢弃。

    protected override void OnPaint(PaintEventArgs pe)
    {
        this.DoubleBuffered = true;
        base.OnPaint(pe);
        Graphics g = pe.Graphics;


        angle += 0.2f;
        if (angle > 359)
        {
            angle = 0;
        }
        using (Matrix matrix = new Matrix())
        {
            matrix.Rotate(angle, MatrixOrder.Append);
            matrix.Translate(300, 200, MatrixOrder.Append);

            g.Transform = matrix;
            pe.Graphics.DrawEllipse(Pens.Red, new Rectangle(50, 60, 50, 50));
        }


        Invalidate();
    }