Jarrod
Jarrod

Reputation: 332

Detecting a mouse click

I have a game, where you click on a button, and it increases an integer by one, however, with the current code that I have, the user can just hold down their mouse and it keeps increasing.

How could I make it so that the user can only press once (per click) to increase their score?

Here's the current code that I have:

public MouseState mouseState;

protected override void Update(GameTime gameTime)
{
     mouseState = Mouse.GetState();
     if (mouseState.LeftButton == ButtonState.Pressed) 
        Managers.UserManager.OverallScore++; 

     base.Update(gameTime);
}

Upvotes: 0

Views: 77

Answers (1)

radical
radical

Reputation: 4424

You could keep track of when the button changes from Pressed to Released state, and run your action at that time, like:

bool leftButtonIsDown; // private instance field

// in your update method
if (Mouse.GetState().LeftButton == ButtonState.Pressed) {
    leftButtonIsDown = true;
} else if (leftButtonIsDown) {
    leftButtonIsDown = false;
    Managers.UserManager.OverallScore++;
}

or do it when it gets pressed, either.

Upvotes: 1

Related Questions