WinForm:按下多个键

sam*_*amy 4 c# winforms

我正在研究像"太空入侵者"这样的简单游戏,我遇到了一个问题.我试图给用户提供从左到右移动的可能性,同时可以使用"空格键"进行拍摄.

我的问题是:当我按下超过1个键时,只有1个功能运行.

这里有一些我试过的东西:

  1. 存储密钥List<Keys>(但我没有找到任何好的方法来执行功能,一切都变得混乱)

    2. key_down事件的正常处理如下:

    protected void Form1_keysDown(object obj, KeyEventArgs e)
    {
        (e.KeyData == Keys.Space)
            spaceShip.FireBullets();
    
        if (e.KeyCode == Keys.Left)
            spaceShip.MoveLeft();
    
        if (e.KeyCode == Keys.Right)
            spaceShip.MoveRight();
     }
    
    Run Code Online (Sandbox Code Playgroud)

我的问题是:什么是使这项工作的好方法?

(对不起我的英语不好)

Han*_*ant 7

按住键盘控制器时重复按键.按下其他键时停止工作.这需要一种不同的方法.

首先,你需要一个枚举来指示宇宙飞船的运动状态,其值为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..
    }
Run Code Online (Sandbox Code Playgroud)