Reputation: 183
I want to play the gunshot sound once I click the left button mouse, but my code is not working.(is running without errors, but not playing the sound)
If I remove the "if condition" and run the game, once the game is running the the first thing will be the gunshot sound.
But if I use the "if condition" it does not work anymore even if I click the left mouse button. I need help to solve this one.
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();
}
}
Upvotes: 0
Views: 400
Reputation: 149
As mentioned in the comments on your original post, you are checking the LeftButton state only when the object is created. What you need to do is add an Update method that does the check and plays the sound effect. I would also move the soundEffect loading out of that loop and do it when you construct or load the object so you have something like this:
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();
}
}
Then in your Game's Update loop, just call gun.Update(gameTime) (where gun is an instance of your gun class)
Upvotes: 3