使用角度移动矩形

Jav*_*erd 7 c# graphics angle drawrectangle

我需要使用角度移动一个矩形.实际上我想改变移动矩形的方向,当它到达我在if语句中的代码中给出的位置时!

我只需要找到如何在60,30,60,120,150,270度移动矩形的方法!

假设如果

          circle.Y>=this.Height-80
Run Code Online (Sandbox Code Playgroud)

看到这个: 在此输入图像描述

我真的需要使用角度来改变矩形运动的方向!所以在某个位置到达我可以根据我自己选择的角度改变矩形方向!这样:

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
Run Code Online (Sandbox Code Playgroud)

正如你在屏幕截图中看到的那样!

我一直在尝试的是:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我一直在努力改变我的条件:

dy = -Math.Asin(1) * dy;
dx = Math.Acos(0) * dx ;
Run Code Online (Sandbox Code Playgroud)

但在这两种情况下都没有发生任何事情,方向仍然相同!我只想将圆圈向上移动90度时到达

circle.Y>=this.Height-80
Run Code Online (Sandbox Code Playgroud)

W0l*_*0ds 3

您需要再次将矩形绘制到某个图像上才能显示。pictureBox1我使用已经定义的-rectangle创建了用于在 上移动和绘制矩形的代码circle

移动矩形:

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));
}
Run Code Online (Sandbox Code Playgroud)

绘制矩形并将其显示在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;
}
Run Code Online (Sandbox Code Playgroud)

单击按钮即可演示:

private void Button1_Click(object sender, EventArgs e)
{
   MoveRectangle(ref circle, 90, 5);
   DrawRectangle(circle);
}
Run Code Online (Sandbox Code Playgroud)