C#按键可以打破物体的运动

时间:2014-12-01 16:39:37

标签: c# key game-physics keydown

我正在创建乒乓球游戏。如果按下移动键,我设法同时移动两条线(图片框)。问题是如果按下一个玩家的控制然后其他玩家只是点击(1次)它会打破其他玩家的移动,这样他就需要再按一次键。我尝试用keypressKeyboard.IsKeyDown修复它,但没有运气。

这是我的代码:

public void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        Keys up1 = (Keys)Enum.Parse(typeof(Keys), form1.p5_text_kontrole_gor1.Text , true);
        Keys down1 = (Keys)Enum.Parse(typeof(Keys), form1.p5_text_kontrole_dol1.Text , true);

        Keys up2 = (Keys)Enum.Parse(typeof(Keys), form1.p5_text_kontrole_gor2.Text, true);
        Keys down2 = (Keys)Enum.Parse(typeof(Keys), form1.p5_text_kontrole_dol2.Text, true);

        if (e.KeyCode == Keys.Escape)
            Application.Exit();

        if(e.KeyCode == up1)
        {
            goup1 = true;
        }
        if (e.KeyCode == down1)
        {
            godown1 = true;
        }
        if (e.KeyCode == up2)
        {
            goup2 = true;
        }
        if (e.KeyCode == down2)
        {
            godown2 = true;
        }
        igra1();
    }

private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        Keys up1 = (Keys)Enum.Parse(typeof(Keys), form1.p5_text_kontrole_gor1.Text, true);
        Keys down1 = (Keys)Enum.Parse(typeof(Keys), form1.p5_text_kontrole_dol1.Text, true);

        Keys up2 = (Keys)Enum.Parse(typeof(Keys), form1.p5_text_kontrole_gor2.Text, true);
        Keys down2 = (Keys)Enum.Parse(typeof(Keys), form1.p5_text_kontrole_dol2.Text, true);

        if (e.KeyCode == up1)
        {
            goup1 = false;
        }
        if (e.KeyCode == down1)
        {
            godown1 = false;
        }

        if (e.KeyCode == up2)
        {
            goup2 = false;
        }
        if (e.KeyCode == down2)
        {
            godown2 = false;
        }
        igra1();
    }

public void igra1()
    {
        if (goup1)
        {
            if (form1.p6_ploscek1.Top > form1.panel6_pongIgra.Top)
                form1.p6_ploscek1.Top -= 15;
        }
        if (goup2)
        {
            if (form1.p6_ploscek2.Top > form1.panel6_pongIgra.Top)
                form1.p6_ploscek2.Top -= 15;
        }
        if (godown1)
        {
            if (form1.p6_ploscek1.Bottom < form1.panel6_pongIgra.Bottom)
                form1.p6_ploscek1.Top += 15;
        }
        if (godown2)
        {
            if (form1.p6_ploscek2.Bottom < form1.panel6_pongIgra.Bottom)
                form1.p6_ploscek2.Top += 15;
        }
    }

1 个答案:

答案 0 :(得分:0)

我相信你依赖于这样一个事实,当你按住它们以使你的游戏块移动时,Windows会重复这些键。按下的第一个键将停止重复,因为按下的新键正在重复。

要解决此问题,请移动计时器控件的Tick()事件。在KeyDown / KeyUp事件中,只需更改变量的状态,该变量表示关联的部分是否应该移动(以及应该移动的方向)。定时器代码将查看状态变量并采取相应的行动......