有一种解决方法
基本上,您有一个计时器,它将以您选择的固定间隔移动图片
打开计时器以继续前进,OnKeyDown
然后将其关闭OnKeyUp
。确保OnKeyDown
您提供可以移动的 X/Y 坐标。OnKeyUp
并在事件中重置该值。
public class MyForm : Form
{
private int deltaX;
private int deltaY;
private const int movementAmount = 10;
private Timer movementTimer = new Timer();
public MyForm()
{
movementTimer.Interval = 100; // make this whatever interval you'd like there to be in between movements
movementTimer.Tick += new EventHandler(movementTimer_Tick);
}
void movementTimer_Tick(object sender, EventArgs e)
{
myMonster.Location = new Point(myMonster.X + deltaX, myMonster.Y + deltaY);
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
switch (e.KeyCode)
{
case Keys.Left:
{
deltaX -=movementAmount;
} break;
case Keys.Right:
{
deltaX += movementAmount;
} break;
case Keys.Up:
{
deltaY -= movementAmount;
} break;
case Keys.Down:
{
deltaY += movementAmount;
} break;
}
UpdateTimer();
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
switch (e.KeyCode)
{
case Keys.Left:
{
deltaX += movementAmount;
} break;
case Keys.Right:
{
deltaX -= movementAmount;
} break;
case Keys.Up:
{
deltaY += movementAmount;
} break;
case Keys.Down:
{
deltaY -= movementAmount;
} break;
}
UpdateTimer();
}
private void UpdateTimer()
{
movementTimer.Enabled = deltaX != 0 || deltaY != 0;
}
}
注意:Switch..Case
当你有很多条件时尝试