如果按下键,如何保存一次单击?

时间:2015-03-29 00:50:07

标签: c# xna

当我按住 A 键时,熊会一直爆炸

我想要的是,当我点击一次仅爆炸一个时,等待另一次按下以爆炸另一个

        KeyboardState board = Keyboard.GetState();
        int newRandomX = rand.Next(800);
        int newRandomY = rand.Next(600);
        float newVelocityX = rand.Next(-5,5);
        float newVelocityY = rand.Next(-5,5);
        Vector2 myVector = new Vector2(newVelocityX, newVelocityY);
        if (bear0.Active && board.IsKeyDown(Keys.A))
        {
            bear0.Active = false;
            boom.Play(bear0.DrawRectangle.Center.X, bear0.DrawRectangle.Center.Y);
        }
        else if (bear1.Active && board.IsKeyDown(Keys.B) && !oldState.IsKeyDown(Keys.B))
        {
            bear1.Active = false;
            boom.Play(bear1.DrawRectangle.Center.X, bear1.DrawRectangle.Center.Y);
        }
        else if (!bear1.Active)
        {
            bear1 = new TeddyBear(Content, WINDOW_WIDTH, WINDOW_HEIGHT, "teddybear1", newRandomX, newRandomY, myVector);
        }
        else if (!bear0.Active)
        {
            bear0 = new TeddyBear(Content, WINDOW_WIDTH, WINDOW_HEIGHT, "teddybear0", newRandomX, newRandomY, myVector);
        }
        board = oldState;
        bear0.Update();
        bear1.Update();
        boom.Update(gameTime);

1 个答案:

答案 0 :(得分:1)

XNA键盘和按钮处理中的约定是维护旧KeyboardState的副本并将其与当前状态进行比较。您可以通过测试密钥当前是否已关闭但确定先前状态表明密钥未关闭来确定何时首次按下该密钥。

MSDN示例:

  

newState 对象中的值与 oldState 对象中的值进行比较。   在此框架中按下了 newState 对象中未按下 oldState 对象的按键。相反,在 newState 对象中按下的键未在 newState 对象中按下的键在此帧期间被释放。

    private void UpdateInput()
    {
        KeyboardState newState = Keyboard.GetState();

        // Is the SPACE key down?
        if (newState.IsKeyDown(Keys.Space))
        {
            // If not down last update, key has just been pressed.
            if (!oldState.IsKeyDown(Keys.Space))
            {
                backColor = 
                    new Color(backColor.R, backColor.G, (byte)~backColor.B);
            }
        }
        else if (oldState.IsKeyDown(Keys.Space))
        {
            // Key was down last update, but not down now, so
            // it has just been released.
        }

        // Update saved state.
        oldState = newState;
    }

更改您的代码:

    if (bear0.Active && board.IsKeyDown(Keys.A))
    {
        bear0.Active = false;
        boom.Play(bear0.DrawRectangle.Center.X, bear0.DrawRectangle.Center.Y);
    }

...为:

    if (bear0.Active && board.IsKeyDown(Keys.A) && !oldState.IsKeyDown(Keys.A) )
    {
        bear0.Active = false;
        boom.Play(bear0.DrawRectangle.Center.X, bear0.DrawRectangle.Center.Y);
    }

...比看熊的状态bear0.Active更好,因为你爆炸熊之后的框架构成一个新的:

    else if (!bear0.Active)
    {
        bear0 = new TeddyBear(Content, WINDOW_WIDTH, WINDOW_HEIGHT, "teddybear0", newRandomX, newRandomY, myVector);
    }

...在下一个if (bear0.Active && board.IsKeyDown(Keys.A)

期间会在下一帧中爆炸

告诉我更多