2013-03-31 46 views
7

我正在製作井字遊戲。我需要檢查一個玩家是否點擊了他們已經點擊過的廣場。XNA - Mouse.Left按鈕在更新中不止一次執行

問題是錯誤顯示在第一次點擊本身。 我更新的代碼是:只要單擊左鍵

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幫我出

回答

10

如何解決:

添加一個新的全局變量鼠標狀態與前一幀存儲:

MouseState oldMouseState; 

在您的更新方法的開始(或結束),添加此,

oldMouseState = mouse; 

而更換

if (mouse.LeftButton == ButtonState.Pressed) 

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

這樣做是什麼檢查你是否做了一次點擊,然後按下鍵,因爲有時候是ou可以保存多個幀的密鑰。

重述一遍:

通過設置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 
}