当您按住它时,您依赖于键盘控制器重复该键。当您按下另一个键时,它会停止工作。这需要不同的方法。
首先,您需要一个枚举来指示飞船的运动状态,其中包含 NotMoving、MovingLeft 和 MovingRight 等值。将该类型的变量添加到您的类中。您将需要 KeyDown和KeyUp 事件。当您获得 KeyDown 时,例如 Keys.Left,然后将变量设置为 MovingLeft。当您获得 Keys.Left 的 KeyUp 事件时,首先检查状态变量是否仍然是 MovingLeft,如果是,则将其更改为 NotMoving。
在您的游戏循环中,使用变量值来移动飞船。一些示例代码:
private enum ShipMotionState { NotMoving, MovingLeft, MovingRight };
private ShipMotionState shipMotion = ShipMotionState.NotMoving;
protected override void OnKeyDown(KeyEventArgs e) {
if (e.KeyData == Keys.Left) shipMotion = ShipMotionState.MovingLeft;
if (e.KeyData == Keys.Right) shipMotion = ShipMotionState.MovingRight;
base.OnKeyDown(e);
}
protected override void OnKeyUp(KeyEventArgs e) {
if ((e.KeyData == Keys.Left && shipMotion == ShipMotionState.MovingLeft) ||
(e.KeyData == Keys.Right && shipMotion == ShipMotionState.MovingRight) {
shipMotion = ShipMotionState.NotMoving;
}
base.OnKeyUp(e);
}
private void GameLoop_Tick(object sender, EventArgs e) {
if (shipMotion == ShipMotionState.MovingLeft) spaceShip.MoveLeft();
if (shipMotion == ShipMotionState.MovingRight) spaceShip.MoveRight();
// etc..
}