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.


1 Answer 1


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;


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);


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


You must log in to answer this question.

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