控制声音仅在XNA中播放一次

时间:2012-07-10 20:05:16

标签: xna

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

// 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();
        }

1 个答案:

答案 0 :(得分:0)

还存储您之前的键盘状态

KeyBoardState prevKeyboardState;

然后在您的更新中

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

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

你基本上只是每秒触发声音很多次,这听起来很糟糕。