0

每次按下键发射导弹时,我都会发出声音。但这听起来不太好。我想这是因为按下键时声音重复了很多次,并且代码在 Update 方法中。我正在寻找一个简单的解决方案,只在按下键时播放一次声音?(我已经测试过第一次使用布尔变量为真,然后在播放声音后为假,但这效果不佳,因为我应该在何时何地再次将其设置为真) 帮助是preciated!

// Fire
if (keyboardState.IsKeyDown(Keys.Space))
{
missile.launchMissile(spaceship.spaceshipPosition, spaceship.spaceshipDirection);

soundExplosion.Play();
}

编辑不起作用的新代码!?

            KeyboardState keyboardState = Keyboard.GetState();

        KeyboardState prevKeyboardState;

        prevKeyboardState = keyboardState;

        keyboardState = Keyboard.GetState();


        if (keyboardState.IsKeyDown(Keys.Space) && prevKeyboardState.IsKeyUp(Keys.Space))
        {
            missile.launchMissile(spaceship.spaceshipPosition, spaceship.spaceshipDirection);
            soundExplosion.Play();
        }
4

1 回答 1

0

也存储您以前的键盘状态

KeyBoardState prevKeyboardState;

然后在你的更新中

prevKeyboardState = keyboardState;
keyboardState = Keyboard.GetState();

if (keyboardState.IsKeyDown(Keys.Space) && prevKeyboardState.IsKeyUp(Keys.Space))
{
  //your code
}

你基本上只是每秒触发无数次声音,让它听起来很糟糕。

于 2012-07-11T13:46:03.230 回答