我想点击左键鼠标后发出枪声,但我的代码无效。(运行没有错误,但没有播放声音)
如果我删除" 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();
}
}
答案 0 :(得分:3)
正如原始帖子的评论中所述,您只在创建对象时检查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)(其中枪是你枪类的一个实例)