【问题标题】:C# Solar System, trouble with planetary orbit mathC# 太阳系,行星轨道数学问题
【发布时间】:2018-03-14 11:58:39
【问题描述】:

我正在编写一个太阳系模拟程序;我只是一个使用 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();
}

【问题讨论】:

  • 你试过交换matrix.Rotate和matrix.Translate的顺序吗?
  • 是的,这并不能解决我的问题。它与我现在这样做时的状态或多或少相同。

标签: c# animation matrix graphics simulation


【解决方案1】:

由于缺少类等,我不得不简化您的代码。但是在此您可以看到它现在可以满足您的需求。

如果您尝试此代码,您会发现 Rotate 和 Translate 的顺序确实很重要,但是当您尝试我的建议时它没有任何效果,因为您在应用变换之前正在绘画。

还请注意,我的矩阵周围有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();
    }

【讨论】:

  • 谢谢!感谢您的帮助。
猜你喜欢
  • 2014-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多