XNA Button - Mouse.Left Launches Several Times in Update

I am making a Tic-Tac-Toe game. I need to check if the player clicked on the square that I already clicked.

The problem is that the error is displayed in the first click. My update code:

MouseState mouse = Mouse.GetState(); int x, y; int go = 0; if (mouse.LeftButton == ButtonState.Pressed) { showerror = 0; gamestate = 1; x = mouse.X; y = mouse.Y; int getx = x / squaresize; int gety = y / squaresize; for (int i = 0; i < 3; i++) { if (go == 1) { break; } for (int j = 0; j < 3; j++) { if (getx == i && gety == j) { if (storex[i, j] == 0) { showerror = 1; } go = 1; if (showerror != 1) { loc = i; loc2 = j; storex[i, j] = 0; break; } } } } } 

showerror set to 0 each time the left button is pressed. My matrix is ​​a 3x3 matrix for storing information. If it is 0, it means that it is already pressed. So, in the loop, I check if store[i,j] == 0 , and then set showerror to 1. Now in the drawing function, I made this call for a shower

 spriteBatch.Begin(); if (showerror == 1) { spriteBatch.Draw(invalid, new Rectangle(25, 280, 105, 19), Color.White); } spriteBatch.End(); 

The problem is, whenever I click on an empty square, it turns into a cross, but an error appears. Please help me

+7
source share
1 answer

How to fix:

Add a new global variable to save the mouse state from the previous frame:

 MouseState oldMouseState; 

At the very beginning (or end) of your update method, add this,

 oldMouseState = mouse; 

And replace

 if (mouse.LeftButton == ButtonState.Pressed) 

from

 if (mouse.LeftButton == ButtonState.Pressed && oldMouseState.LeftButton == ButtonState.Released) 

This means that you made one click by pressing a key, then press, because sometimes you can hold the key for several frames.

To do the following:

By setting oldMouseState before updating currentMouseState (or after you are done with it), you guarantee that oldMouseState will be one frame per currentMouseState . Using this, you can check if the button was pressed on the previous frame, but no longer, and process the input accordingly. A good idea to extend this is to write some extension methods such as IsHolding() , IsClicking() , etc.

In simple code:

 private MouseState oldMouseState, currentMouseState; protected override void Update(GameTime gameTime) { oldMouseState = currentMouseState; currentMouseState = Mouse.GetState(); //TODO: Update your code here } 
+10
source

All Articles