如果条件在XNA中播放声音,则不播放声音
本文关键字:播放声音 条件 XNA 如果 | 更新日期: 2023-09-27 18:27:42
我想在单击鼠标左键后播放枪声,但我的代码不起作用。(运行时没有错误,但没有播放声音)
如果我去掉"如果条件"并运行游戏,一旦游戏运行,第一件事就是枪声。
但是,如果我使用"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();
}
}
正如在原始帖子的评论中所提到的,只有在创建对象时才检查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即可。更新(gameTime)(其中gun是您的gun类的实例)