2012-03-15 118 views
11

我有一個2D遊戲,其中只使用鼠標作爲輸入。 我該如何做到這一點,以便當鼠標懸停在Texture2D對象上,Texture2D和鼠標光標發生變化時,以及當紋理被點擊時,它會移動到另一個位置。2D XNA遊戲鼠標點擊

簡而言之,我想知道當我將鼠標懸停或點擊一個Texture2D時如何做某些事情。

+0

這屬於在http ://gamedev.stackexchange.com/ – RQDQ 2012-03-15 12:09:06

回答

30

在XNA中,您可以使用Mouse class來查詢用戶輸入。

這樣做最簡單的方法是檢查每個幀的鼠標狀態並作出相應的反應。鼠標位於某個區域內嗎?顯示不同的光標。在此框架中按下右按鈕?顯示一個菜單。等

var mouseState = Mouse.GetState(); 

獲取屏幕座標鼠標位置(相對於左上角):

var mousePosition = new Point(mouseState.X, mouseState.Y); 

更改當鼠標的特定區域內的紋理:

Rectangle area = someRectangle; 

// Check if the mouse position is inside the rectangle 
if (area.Contains(mousePosition)) 
{ 
    backgroundTexture = hoverTexture; 
} 
else 
{ 
    backgroundTexture = defaultTexture; 
} 

點擊鼠標左鍵時做點什麼:

if (mouseState.LeftButton == ButtonState.Pressed) 
{ 
    // Do cool stuff here 
} 

請記住,您將始終擁有當前框架的信息。所以儘管點擊按鈕期間可能會發生很酷的事情,但它會在發佈後立即停止。

要檢查一個點擊,你就必須存儲的最後一幀的鼠標狀態,比較有什麼變化:

// The active state from the last frame is now old 
lastMouseState = currentMouseState; 

// Get the mouse state relevant for this frame 
currentMouseState = Mouse.GetState(); 

// Recognize a single click of the left mouse button 
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed) 
{ 
    // React to the click 
    // ... 
    clickOccurred = true; 
} 

你可以使其更加先進以及使用事件。因此,您仍然可以使用上面的代碼片段,而不是直接包含要觸發事件的代碼:MouseIn,MouseOver,MouseOut。 ButtonPush,ButtonPressed,ButtonRelease等

+0

Rectangle.Contains需要一個點,所以我不知道爲什麼你將Mouse.GetState()返回的Point轉換爲Vector。 – ClassicThunder 2012-03-15 15:32:42

+0

非常感謝,lucius – 2012-03-16 21:46:52

+0

但是我怎麼能在任何位置關聯點擊和紋理。 當我離開的時候點擊了它的任何位置都不是特定的矩形! – 2012-03-16 22:01:09

-1

我只想補充一點,鼠標單擊代碼可以簡化,使您不必爲此做出一個變量:

if (Mouse.GetState().LeftButton == ButtonState.Pressed) 
    { 
     //Write code here 
    } 
+0

這與原始問題有什麼關係? – jeteon 2016-03-04 14:32:18