我想在单击鼠标左键后播放枪声,但是我的代码不起作用。(正在运行,没有错误,但没有播放声音)
如果我删除“如果条件”并运行游戏,则一旦游戏运行,第一件事就是枪声。
但是,如果我使用“如果条件”,即使单击鼠标左键也无法正常工作。我需要帮助来解决这一问题。
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/