Search code examples
c#monogame

Mouse button keeps being pressed instead of clicking


I'm currently working on a game in monogame. The game is heavily based on clicking buttons and this is where the problem occurs. Whenever I hold down the left mouse button and then move it over a button in the game, that button gets clicked instantly.

I've tried to fix the issue in many ways, by rearrange the if statements in different ways, adding an extra bool to check if the mouse button is clicked, etc.. but without any luck. Haven't found any solutions anywhere either.

public override void Update(GameTime gameTime)
{
    MouseState state = Mouse.GetState();

    if (new Rectangle((position - ElementCenter).ToPoint(), sprite.Bounds.Size)
           .Contains(state.Position) && oldState.LeftButton == ButtonState.Released)
    {
        renderColor = Color.LightSlateGray;
        if (state.LeftButton == ButtonState.Pressed &&
            oldState.LeftButton == ButtonState.Released)
        {
            switch (button)
            {
                case "UI/submit":
                    if (GameWorld.Instance.Team.UserTeamName.Length > 0)
                    {
                        GameWorld.Instance.SubmitTeamName();
                    }
                    break;
                case "UI/teammanager":
                    GameWorld.Instance.TeamManager();
                    break;
                default:
                    break;
            }
        }
    }
    else
    {
        renderColor = Color.White;
    }
    oldState = state;
}

Ideally I would like that a button gets clicked only if the left mouse button has been released before clicking a button.


Solution

  • If oldState is declared as instance field, different instances of this class will have different versions of it. I.e., the old state may get lost.

    Declare oldState as static!

    private static MouseState oldState = Mouse.GetState();