【问题标题】:Move an Ellipse in angular direction沿角度方向移动椭圆
【发布时间】:2014-05-13 22:19:16
【问题描述】:

嘿,我是 C# 图形编程的新手。我需要知道如何在我的窗口中沿角度方向移动椭圆。我已经使用我的代码成功地将我的椭圆移动到默认方向。


我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Paddle_Test
{
    public partial class Form1 : Form
    {
        Rectangle rec;
        int wLoc=0;
        int hLoc=0;
        int dx=3;
        int dy=3;

    public Form1()
    {
     InitializeComponent();
     rec = new Rectangle(wLoc,hLoc , 100, 10);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Refresh();
    }

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.FillEllipse(new SolidBrush(Color.Blue), rec);

    }

    private void timer_Tick(object sender, EventArgs e)
    {
        //moving inside my timer
        rec.X += dx;  
        rec.Y += dy;  
    }


}
  }

简单来说,我的椭圆只是沿对角线移动!所以简单来说问题是我是否可以像 30' 或 80' 或指定角度那样移动它!


【问题讨论】:

    标签: c# winforms move drawrectangle drawellipse


    【解决方案1】:

    Rectangle.X / Y 是int,加到这样的整数上至少会在 X 或 Y 上加 1,从而导致对角线移动。

    dx 和 dy 应该是 floatdouble。对于 X 和 Y 坐标,您也必须有一个浮点变量并用它进行计算。计算完成后,您可以将自己的 X / Y 分配给矩形。

    从你的代码中你应该多写:

    public partial class Form1 : Form
    {
        Rectangle rec;
        int wLoc=0;
        int hLoc=0;
        double xpos=0;
        double ypos=0;
        double dx=0.3;
        double dy=0.6;
    

    然后像这样在你的计时器中计算:

    xpos += dx;
    ypos += dy;
    rec.X = xpos;
    rec.Y = ypos;
    

    可以在计时器中通过否定 dx 或 dy 来完成墙上的反射,具体取决于您到达的一侧。

    如果您想使用角度作为输入来计算 dx 和 dy,您可以这样做:

    xpos += cos(angleInDegrees / 360.0 * 2 * Math.PI) * speed;
    ypos += -sin(angleInDegrees / 360.0 * 2 * Math.PI) * speed;
    rec.X = xpos;
    rec.Y = ypos;
    

    速度是每次计时器调用的像素移动量。

    【讨论】:

    • 我编辑了我的代码,如果我更改了 dx=5 和 dy=2,它会加快移动速度
    • 我的意思是,您应该将 dx 和 dy 设置为更小的值。改为将其设置为 0.3 或 0.6。您不应该使用整数进行计算。
    • @user3411946 看我的例子
    • 你的代码给了我一些想法,所以我正在处理你的帮助会给 +1 等待我的标记
    【解决方案2】:

    我相信您正在寻找一些基本的三角函数,例如:

    x = cos(degrees) * maxX;
    y = sin(degrees) * maxY;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多