7

角度を使用して長方形を移動する必要があります。実際には、if ステートメントのコードで指定した場所に到達したときに、移動する四角形の方向を変更したいと考えています!

長方形を 60、30、60、120、150、270 度で移動する方法を見つける方法が必要なだけです。

もし

          circle.Y>=this.Height-80

これを参照してください: ここに画像の説明を入力

角度を使用して長方形の移動方向を実際に変更する必要があります。特定の場所に達すると、自分の選択した角度に応じて長方形の方向を変更できます! そのような:

if(circle.Y>=this.Height-80)
    move in the direction of 90 degrees

if(circle.X>=this.Width-80)
    move in the direction of 60 degree

スクリーンショットでわかるように!

私が試したことは次のとおりです。

public partial class Form1 : Form
{
    Rectangle circle;
    double dx = 2;
    double dy = 2;

    public Form1()
    {
        InitializeComponent();
        circle = new Rectangle(10, 10, 40, 40);
    }

    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.Red), circle);
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        circle.X += (int)dx;
        circle.Y += (int)dy;
        if (circle.Y>=this.Height-80)
        {
            dy = -Math.Acos(0) * dy/dy; //here i want to change the direction of circle at 90 degrees so that it should go up vertically straight with same speed
        }
        this.Refresh();
    }
}

問題は、条件を次のように変更しようとしているということです。

dy = -Math.Asin(1) * dy;
dx = Math.Acos(0) * dx ;

しかし、どちらの場合も何も起こらず、方向は同じままです! 円が 90 度に達したときに、円を逆上方向に移動したいだけです。

circle.Y>=this.Height-80
4

3 に答える 3

3

画像を表示するには、長方形を再度描画する必要があります。pictureBox1既に定義されているcircle-rectangleを使用して、 で四角形を移動および描画するためのこのコードを作成しました。

長方形の移動:

public void MoveRectangle(ref Rectangle rectangle, double angle, double distance)
{
   double angleRadians = (Math.PI * (angle) / 180.0);
   rectangle.X = (int)((double)rectangle.X - (Math.Cos(angleRadians) * distance));
   rectangle.Y = (int)((double)rectangle.Y - (Math.Sin(angleRadians) * distance));
}

四角形を描画し、 に表示しますPictureBox

public void DrawRectangle(Rectangle rectangle)
{
   Bitmap bmp = new Bitmap(pictureBox1.Width, pictureBox1.Height);
   using (Graphics g = Graphics.FromImage(bmp))
   {
      g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
      g.FillEllipse(new SolidBrush(Color.Red), rectangle);
   }
   pictureBox1.Image = bmp;
}

ボタンをクリックしてデモを行います:

private void Button1_Click(object sender, EventArgs e)
{
   MoveRectangle(ref circle, 90, 5);
   DrawRectangle(circle);
}
于 2014-06-05T05:37:08.870 に答える
1

acos と asin は sin と cos の逆関数なので、これら 2 つの関数の出力は角度 (通常はラジアン) です。これにより、コードが正しくなくなります。

オイラー角を使用すると非常に面倒になる可能性があるため、ベクトルと行列の数学をよく読むことを強くお勧めします。

したがって、位置ベクトル P と移動ベクトル M があり、現在の位置は次のようになります。

 P' = P + M.t

ここで、t は時間、P は元の位置、P' は現在の位置です。

次に、方向を変更したい場合は、回転行列を作成し、移動ベクトル M にこの回転行列を掛けます。

ここでの利点は、ベクトルに Z コンポーネントを追加し、行列のサイズを大きくすることで、2D システムから 3D システムに移行できることです。

于 2014-06-02T15:52:00.657 に答える