我正在创建一个模拟汽车游戏的应用程序,它使用两个键,左键和右键。我正在使用椭圆并在两个方向上移动它。当我启动应用程序并将椭圆移动到右键时,它工作正常,当我按下左键时它会冻结,我正在使用另一个必须不断向下移动的椭圆。下面是我用来移动椭圆的两个函数。以及表单的 key_down 事件:
public void MoveLeft()
{
if (startPoint.Y > 100)
{
startPoint.Y = 1;
}
while (startPoint.Y > 1)
{
graphics.Clear(BackColor);
if (startPoint.Y > this.ClientSize.Height)
startPoint.Y = 0;
startPoint.Y += 5;
graphics.DrawEllipse(Pens.Black, new Rectangle(carPoint, new Size(100, 100)));
graphics.FillEllipse(new SolidBrush(Color.Green), new Rectangle(carPoint, new Size(100, 100)));
Move();
System.Threading.Thread.Sleep(50);
}
}
public void MoveRight()
{
while (startPoint.Y > 1)
{
if (startPoint.Y > this.ClientSize.Height)
startPoint.Y = 0;
startPoint.Y += 5;
carPoint = new Point(100, 250);
graphics.DrawEllipse(Pens.Black, new Rectangle(carPoint, new Size(100, 100)));
graphics.FillEllipse(new SolidBrush(Color.Green), new Rectangle(carPoint, new Size(100, 100)));
Move();
System.Threading.Thread.Sleep(50);
graphics.Clear(BackColor);
}
}
public void Move()
{
graphics.DrawEllipse(Pens.Black, new Rectangle(startPoint, new Size(100, 100)));
graphics.FillEllipse(new TextureBrush(image), new Rectangle(startPoint, new Size(100, 100)));
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyData)
{
case Keys.Right:
{
moveCar = new Thread(new ThreadStart(MoveRight));
moveCar.Start();
}
break;
case Keys.Left:
{
if (moveCar != null)
{
moveCar.Abort();
moveCar = null;
}
moveCar = new Thread(new ThreadStart(MoveLeft));
moveCar.Start();
}
break;
}
}