XNA - Mouse.Left按钮获取更新多次执行(XNA - Mouse.Left Butt

2019-08-18 10:13发布

我想提出一个井字棋游戏。 我需要检查,如果玩家点击他们已经点击了一个正方形。

问题是在显示第一个错误单击本身。 我更新的代码是:

    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只要单击左键设置为0。 我矩阵是用于存储信息的3x3矩阵。 如果是0,这意味着它已经被clicked.So在循环我检查,如果store[i,j] == 0然后设置showerror 1。现在,在绘制函数我做了这个呼吁showerror

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

问题是,每当我对空方点击它变成十字但误差会shown.Please帮助我

Answer 1:

怎么修:

添加一个新的全局变量鼠标状态与前一帧存储:

MouseState oldMouseState;

开始的时候(或结尾)你的更新方法,添加此,

oldMouseState = mouse;

和替换

if (mouse.LeftButton == ButtonState.Pressed)

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

这样做是检查,如果你做一个点击,其释放的键再按下,因为有时你可能持有多个帧的关键。

为了回顾:

通过设置oldMouseState在更新之前currentMouseState (或者你用它做后),您garantee那oldMouseState将在后面一帧currentMouseState 。 使用此您可以检查一个按钮下跌前一帧,但现在不是了,并相应地处理输入。 一个好主意,延长这是写一些扩展方法,如IsHolding() IsClicking()等。

在简单的代码:

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


文章来源: XNA - Mouse.Left Button gets executed more than once in Update