2010-03-07 128 views
4

這一直困擾着我lately-當我使用一些代碼象下面增加選擇每次鼠標點擊: if (m.LeftButton == ButtonState.Pressed) currentSelection++; 然後由一噸currentSelection增加,僅僅是因爲這個代碼是在我的Update()函數和設計中,運行每一幀,因此增加currentSelection。幾乎沒有機會點擊並釋放足夠快的速度,以防止currentSelection增加多個。增加數每一次鼠標點擊/按鍵在XNA

現在我的問題是我應該怎麼做,所以每次我點擊鼠標一次,它只增加currentSelection一次,直到下次再次點擊。

回答

6

您需要比較當前的鼠標狀態和上次更新的鼠標狀態。

在你的類,你會已經MouseState mouseStateCurrent, mouseStatePrevious;聲明,所以它會是這樣的:

mouseStateCurrent = Mouse.GetState(); 

if (mouseStateCurrent.LeftButton == ButtonState.Pressed && 
    mouseStatePrevious.LeftButton == ButtonState.Released) 
{ 
    currentSelection++; 
} 

mouseStatePrevious = mouseStateCurrent; 

所以它會檢測你按下它,以前的時候,那你鬆開 - 才把它被認爲是作爲點擊,它將添加到currentSelection

+0

我收到這個奇怪的錯誤,它說&&操作數不能用於ButtonState – DMan 2010-03-07 04:09:07

+1

哈哈,沒關係,我意識到它是你用'='而不是'=='。 =)這工作,謝謝。 – DMan 2010-03-07 04:09:59

+0

我在==修復中編輯過。 – Ricket 2010-03-09 18:49:25