【问题标题】:How can I move image with the KeyBoard using 2 keys?如何使用 2 个键使用键盘移动图像?
【发布时间】:2013-01-22 21:02:29
【问题描述】:

我有一个我正在努力解决的问题.. 我想使用键盘向左、向右、向上或向下并以对角线方式移动图像。 我在网上搜索并发现,要使用 2 个不同的键,我需要记住前一个键,因此我使用的是 bool 字典。

在我的主 Form 类中,KeyDown 事件如下所示:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    baseCar.carAccelerate(e.KeyCode.ToString().ToLower());
    carBox.Refresh(); //carbox is a picturebox in my form that store the image I want to move.
}

我的 KeyUp 事件:

private void Form1_KeyUp(object sender, KeyEventArgs e)
{
    baseCar.carBreak(e.KeyCode.ToString().ToLower());
}

我的绘画活动:

private void carBox_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawImage(Car, baseCar.CharPosX, baseCar.CharPosY); // Car is just an image
}

还有我的 baseCar 类:

私人字典键D = new Dictionary(); // 有一个方法可以设置 W|A|S|D Keys,比如:KeysD.Add("w",false)

    public void carAccelerate(string moveDir)
    {       
        KeysD[moveDir] = true;
        moveBeta();
    }
    public void moveBeta()
    {
        if (KeysD["w"])
        {
            this.CharPosY -= this.carMoveYSpeed;
        }
        if (KeysD["s"])
        {
            CharPosY += carMoveYSpeed;
        }
        if (KeysD["a"])
        {
            CharPosX -= carMoveXSpeed;
        }
        if (KeysD["d"])
        {
            CharPosX += carMoveXSpeed;
        }
    }
    public void carBreak(string str)
    {
        KeysD[str] = false;
    }

无论如何它都有效,但我的问题是我无法回到第一个按下的键,例如:

我按 W 向上移动,然后按 D 键进入对角线,但是当我释放 D 键时它不会再次向上移动,因为 KeyDown 事件“已死”并且不会再次调用 carAccelerate() 方法。 我不知道如何解决它..

谁能帮帮我? 也许有更好的方法来处理密钥?我愿意接受任何想法! 我希望你能理解,我的英语不是最好的:S

【问题讨论】:

    标签: c# forms class events


    【解决方案1】:

    存储所有键状态,不要在按键时设置动画,但例如使用计时器。

    然后:

    KeyDown(key)
    {
       KeyState[key] = true;
    }
    
    KeyUp(key)
    {
       KeyState[key] = false;
    }
    
    Timer_Tick()
    {
        Animate();
    }    
    
    Animate()
    {
        if (KeyState["W"])
        {
            // Accelerate
        }
        if (KeyState["S"])
        {
            // Decelerate
        }
    
    }
    

    然后在 KeyDown 方法中,您可以检查是否存在冲突键(如果同时按下加速 + 减速会怎样,等等)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 2015-08-14
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多