I want to change a boolean when I click the left mouse button, but it doesn't work as expected. I use this method:

if (m.LeftButton == ButtonState.Released && m_Old.LeftButton == ButtonState.Pressed)
   if (second)
      second = false; // Boolean changes
   } else
      second = true; // Boolean changes

I need a way to tell the code that I only want one change. When I click the left mousebutton, the second boolean changes constantly. The reason for this is that the code keeps executing until m_Old (the old mousestate) is updated. (m & m_Old must be different for this code to run)

An example (when I click the left mouse button once| these are the results for the second boolean):

enter image description here

My mouse update code:

// Mouse stuff
oldMouse = mouse;
mouse = Mouse.GetState();
  • \$\begingroup\$ It's kind of difficult trying to figure out what you're trying to achieve with this code by looking at it. Can you describe the end goal? \$\endgroup\$ – craftworkgames Mar 28 '16 at 23:51
  • \$\begingroup\$ @craftworkgames I try to change a boolean from true to false and the other way around. This is usefull because I can now use two different Mouse clicks (true & false) for the same button. I use these clicks for picking up and dropping an item in the inventory in my game. I already found another solution to this problem. I use a stopwatch now instead of a boolean variable but I'm still curious for this answer. \$\endgroup\$ – Jelle Mar 28 '16 at 23:58

Ah I think I understand the problem now. It's not really clear from the code you've posted what the problem is but I think it might have something to do with second being declared in the local scope.

I tested the code below and I believe it's working as you'd expect. I've renamed some of the variables to hopefully make it a little more understandable. It wasn't really clear from the question if second is a member variable but I believe it needs to be to maintain state across refreshes.

private MouseState _previousMouseState;
private bool _second;

protected override void Update(GameTime gameTime)
    var mouseState = Mouse.GetState();

    if(mouseState.LeftButton == ButtonState.Released && _previousMouseState.LeftButton == ButtonState.Pressed)
        _second = !_second;

    _previousMouseState = mouseState;


Since you're essentially just flipping a flag the if statement in the middle can be reduced to one line. Either way should work though.

| improve this answer | |
  • \$\begingroup\$ Thanks, it works now. My old_Mouse update was in another class so it was a few milliseconds to slow so the variable could change a few times... \$\endgroup\$ – Jelle Mar 31 '16 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.