我试图使用MyRectangle.Offset(x, y)
移动一个矩形,但它没有移动。从我发现它的东西,我正在取消它的副本,而不是矩形本身,所以现在我创建一个具有所需坐标的新矩形,然后用这个替换旧的矩形。它适用于第一次移动,但是当我想第二次移动矩形时,它就会消失。我不知道为什么。以下是我的一些代码:
private void button2_Click(object sender, EventArgs e)
{
spawn = "movement";
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
switch (spawn)
{
case "movement":
foreach(aircraft acft in aircrafts) // aircrafts is an array of of class aircraft I have created.
// It consist of many variables (mostly integers), and the rectangle that is supposed to move
{
acft.Move_calculate(e.Graphics);
}
spawn = string.Empty; // clearing the string to prevent creating an infinite loop
break;
....
public void Move_calculate(Graphics g)
{
speed = nahodnacisla.Next(14, 21);
if (points[passed].X > x_coordinate && points[passed].Y > y_coordinate) // have four of these conditons (x > or <, y > or <)
{
points[passed].X = Bx; // points is an array of Point, those are the points the rectangle will be moving around (move slowly to one, then to another)
points[passed].Y = By;
distanceForAlfaX = Bx - x_coordinate; // x_coordinate is currect coordinate of the rectangle
distanceForAlfaY = By - y_coordinate;
alpha =(distanceForAlfaY/distanceForAlfaX); // tangens alpha
x_change = (int)(speed * (Math.Cos(alpha))); // using the tangens counting the rectagle movement relative to x axis
y_change = (int)Math.Sqrt(((speed * speed) + (x_change * x_change))); // calculate movement relative to y axis using Pythagoras theorem
x_coordinate += x_change; // update the coordinates
y_coordinate += y_change;
Pen p = new Pen(Color.Turquoise, 2);
r = new Rectangle(x_coordinate, y_coordinate, 5, 5); // replace the original rectangle named r with a new one
g.DrawRectangle(p, r);
p.Dispose();
正如我所说,第一次,矩形根据速度设置正确移动。但是当我再次单击“移动”按钮(稍后将定时器设置为两秒)时,它会消失。为什么呢?