【问题标题】:If condition play sound in XNA, does not play sound?如果条件在 XNA 中播放声音,不播放声音?
【发布时间】:2014-10-24 20:05:01
【问题描述】:

我想在单击鼠标左键后播放枪声,但我的代码不起作用。(运行时没有错误,但没有播放声音)

如果我删除“if 条件”并运行游戏,一旦游戏运行,第一件事就是枪声。

但是,如果我使用“if 条件”,即使我单击鼠标左键,它也不再起作用。我需要帮助来解决这个问题。

class Gun
        {
            Texture2D gun;
            Vector2 position;
            SoundEffect soundEffect;

            public Gun(ContentManager Content)
            {
                gun = Content.Load<Texture2D>("Gun");
                position = new Vector2(10, 10);
                MouseState mouse = Mouse.GetState();

                if (mouse.LeftButton == ButtonState.Pressed)
                {
                    soundEffect = Content.Load<SoundEffect>("gunshot");
                    soundEffect.Play();
                }
            }

【问题讨论】:

  • 在构造函数中这样做有意义吗?这不是你在更新期间做的事情吗?
  • 好吧,你只是在constructor中检查音效,你需要在更新循环中检查鼠标状态,以便if语句执行多次。
  • 谢谢,是的,我将 if 语句放在主类的更新循环中是有道理的。现在它按预期工作了。

标签: c# audio xna


【解决方案1】:

正如您原始帖子中的 cmets 所述,您仅在创建对象时检查 LeftButton 状态。您需要做的是添加一个 Update 方法来执行检查并播放声音效果。我还会将 soundEffect 加载移出该循环,并在您构造或加载对象时执行它,这样您就有了这样的东西:

    public class Gun
    {
        Texture2D gun;
        Vector2 position;
        SoundEffect soundEffect;
        MouseState _previousMouseState, currentMouseState;

        public Gun(ContentManager Content)
        {
            gun = Content.Load<Texture2D>("Gun");
            soundEffect = Content.Load<SoundEffect>("gunshot");
            position = new Vector2(10, 10);
        } 


        public void Update(GameTime gameTime)
        {
            // Keep track of the previous state to only play the effect on new clicks and not when the button is held down
            _previousMouseState = _currentMouseState;
            _currentMouseState = Mouse.GetState();
            if(_currentMouseState.LeftButton == ButtonState.Pressed && _previousMouseState.LeftButton != ButtonState.Pressed)
               soundEffect.Play();
        }
    }

然后在你的游戏更新循环中,调用 gun.Update(gameTime) (其中 gun 是你的 gun 类的一个实例)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 2015-03-20
    • 2011-02-25
    • 2020-02-15
    相关资源
    最近更新 更多