c# - 如果条件在XNA中播放声音,是否不播放声音?

标签 c# audio xna

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

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

但是,如果我使用“如果条件”,即使单击鼠标左键也无法正常工作。我需要帮助来解决这一问题。

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

最佳答案

如原始帖子的评论中所述,仅在创建对象时才检查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();
        }
    }

然后在游戏的Update循环中,仅调用gun.Update(gameTime)(其中gun是您的gun类的实例)

关于c# - 如果条件在XNA中播放声音,是否不播放声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26555433/

相关文章:

C# XNA 4.0 异常 : "Cannot Open File"

c# - 在 .NET 4.0 中使用 Web 服务时出现连接错误

c# - c# 多个窗体之间的通信

android - 无法对非静态方法 getAssets() 进行静态引用 - 在 fragment 中播放音频时遇到问题

java - 我需要一些帮助,用 java 读取 WAV 文件并确定其各种幅度

c# - 从多个 Texture2D 生成一个 Texture2D

c# - 统一: Android touch on Gui texture

c# - Rijndael:多台机器上的相同输入/不同输出

ios - 为什么当我暂停 AVAudioPlayer 时锁屏音频控件会消失?

c# - 在 XNA 中按下按键时等待