0
\$\begingroup\$

I have been trying different things all day to get the answer. What I need is a sound to play one time when I enter a given rectangle I need the sound to fire one time and never fire again until I exit the rectangle.It is easy for me to find out if the mouse is over the rect by using the contains() method but the problem comes when the sound gets played it just keeps looping.I added a check to see if the sound state is not playing and that stops it from just making random noise but it still loops help me obi wan.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

In a polling-based system like XNA's you must store the previous input state as well as the current one, in order to detect state transitions.

So just as you would use code like this to detect a click:

var mouseState = Mouse.GetState(); // <- top of Update method

bool mouseDown = lastMouseState.LeftButton == ButtonState.Released
                 && mouseState.LeftButton == ButtonState.Pressed;

if(mouseDown)
    DoSomething();

lastMouseState = mouseState; // <- bottom of Update method

You would use code like this to detect the mouse entering:

bool mouseEnter = !rect.Contains(lastMouseState.X, lastMouseState.Y)
                  && rect.Contains(mouseState.X, mouseState.Y);

if(mouseEnter)
    PlaySound();

(And so on for mouse leaving, mouse button up, etc.)

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .